<?php

namespace control;

/*
*员工档案类
*/

class staffProfilesClass extends adIndexClass
{
    private const page = 'staffProfiles';
    private const table = 'staff';
    private const title = '员工档案';
    private array $warnOption = ['10' => '待签合同', '20' => '待参保', '30' => '合同将到期'];
    public array $stateOption = ['试用', '转正', '留职', '离职'];
    public array $sexOption = ['男', '女'];

    public function homeOptions($isAsync = true): string
    {
        //生成查询表单
        $option = [];
        for ($i = 1; $i <= 12; $i++) {
            $option[] = sprintf("%02d", $i);
        }
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('staffProfiles.table.state') => checkbox(array(
                        "name" => "state",
                        "value" => $this->stateOption,
                        "checked" => array("试用", '转正', '留职'),
                    )),
                ],
                [
                    L('staffProfiles.table.name')     => text(array("name" => "name")),
                    L('staffProfiles.table.department') => selectMultiple(["name" => "departmentId", 'table' => "department", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200', 'title' => '请选择']),
                    L('staffProfiles.table.job')   => selectMultiple(["name" => "jobId", 'table' => " job", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200', 'title' => '请选择']),
                ],
                [
                    L('staffProfiles.table.sex') => select(array("name" => "sex", "option" => $this->sexOption)),
                    L('staffProfiles.table.tel')   => text(array("name" => "tel")),
                    L('staffProfiles.table.idCard')   => text(array("name" => "idCard")),
                ],
                [
                    L('staffProfiles.table.birthDate') => select(array("name" => "month", "option" => $option)),
                    L('staffProfiles.table.warn_message') => select(array("name" => "warnTip", "option" => $this->warnOption)),
                    L('staffProfiles.table.workFlow') => select(array("name" => "workFlow", "option" => ['待复核', '已复核'])),
                ],
                [
                    '入职日期' => text(array("name" => "registerDate", 'laydate' => ['type' => 'date', 'range' => '~']))
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $url = root . "control/adIndex.html?cla=" . self::page;
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span  onclick=\"newIframe('" . L('staffProfiles.detail.staff_info') . "','" . $url . "&fun=editPage')\" class='spanButton marginl0'>" . L('staffProfiles.button.addNew') . "</span>\n";
        }
        if ($this->power(self::page, "audit")) {
            $button .= "<span class='spanButton' onclick=\"layer('" . self::page . "', 'review', {})\">" . L('staffProfiles.button.batchReview') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('" . self::page . "', 'operate', {'act': 'del'})\">" . L('staffProfiles.button.del') . "</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."',importFun:'import'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'recordSearch':
                $tr = [
                    'type'      => [
                        'name'  => L('staffProfiles.detail.orderType'),
                        'width' => 450,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => L('staffProfiles.detail.orderNo'),
                        'width' => 450,
                        'sort' => 1,
                    ],
                    'recordDate'  => [
                        'name'  => L('staffProfiles.detail.date'),
                        'width' => 450,
                        'sort' => 1,
                    ]
                ];
                break;
            default:
                $tr = [
                    'stNo'      => [
                        'name'  => L('staffProfiles.table.orderNo'),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => L('staffProfiles.table.name'),
                        'width' => 100,
                    ],
                    'department'  => [
                        'name'  => L('staffProfiles.table.department'),
                        'width' => 200,
                    ],
                    'job'         => [
                        'name'  => L('staffProfiles.table.job'),
                        'width' => 150,
                    ],
                    'idCard'          => [
                        'name'  => L('staffProfiles.table.idCard'),
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'sex'        => [
                        'name'  => L('staffProfiles.table.sex'),
                        'width' => 50,
                    ],
                    'tel'    => [
                        'name'  => L('staffProfiles.table.tel'),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'birthDay'        => [
                        'name'  => L('staffProfiles.table.birthDate'),
                        'width' => 100,
                    ],
                    'entryDate'        => [
                        'name'  => L('staffProfiles.table.entryDate'),
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'contractDate'        => [
                        'name'  => L('staffProfiles.table.contractDate'),
                        'width' => 120,
                    ],
                    'insureDate'        => [
                        'name'  => L('staffProfiles.table.insureDate'),
                        'width' => 100,
                    ],
                    'endDate'        => [
                        'name'  => L('staffProfiles.table.endDate'),
                        'width' => 100,
                    ],
                    'state'        => [
                        'name'  => L('staffProfiles.table.state'),
                        'width' => 80,
                    ],
                ];
        }
        return $tr;
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        $warnDay = para('workContractWarnDay');
        //like查询数组
        $like = array(
            "st.name" => $this->post('name'),//姓名
            "st.tel" => $this->post('tel'),//手机号
            "ta.idCard" => $this->post('idCard'),//身份证号
        );
        //全等查询数组
        $equal = array(
            "st.jobId" => $this->post('jobId'),//职位
            "ta.sex" => $this->post('sex'),//性别
            "st.workFlow" => $this->post('workFlow'),
        );
        $and = "";
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and st.jobId in (select id from job where departmentId = '{$this->post('departmentId')}')";
        }
        if ($this->post('registerDate')) {
            $and .= self::timeComparison($this->post('registerDate'), field: 're.entryDate');
        }
        if (!empty($this->post('state'))) {
            $and .= " and st.state in ('" . implode("','", $this->post('state')) . "') ";
        }
        if (!empty($this->post('month'))) {
            $and .= " and date_format(ta.birthDay,'%m') = '{$this->post('month')}' ";
        }
        if ($this->post('warnTip')) {
            $and .= match ($this->post('warnTip')) {
                '10' => " and st.stid not in (select staffId from staff_contract where workFlow ='生效中' and isClose = 0) ",
                '20' => " and st.stid not in (select staffId from staff_insure where workFlow in ('参保中','待停保')) ",
                '30' => " and st.stid in (select staffId from staff_contract where workFlow = '生效中' and DATEDIFF(signEndDate,DATE_FORMAT(now(),'%Y-%m-%d')) <= '$warnDay' and isClose = 0) ",
                default => ""
            };
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'entryDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            'field' => " ta.*,re.entryDate,st.stid,st.jobId as realJobId,st.state,st.orderNo as stNo,st.name,st.manager,st.workFlow",
            "table" => self::table . " as st left join talent_pool as ta on st.talentId = ta.id left join staff_entry_record as re on (re.talentId = st.talentId and re.id not in (select entryId from staff_quit_record where isConfirm = 1))",
            "where" => $where,
            "order" => $orderBy['orderBy'],
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch(self::page.'-homeSearch');
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $_SESSION[self::page]['sql'] = $page['fullSql'];

        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['stid']),
                'edit' => array("title" => L('staffProfiles.button.edit'), "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=entry&id=" . $array['stid'] . "')"),
                "detail" => array("title" => L('staffProfiles.detail.staff_info'), "click" => "newIframe('" . L('staffProfiles.detail.staff_info') . "','" . $url . "&fun=detail&id=" . $array['stid'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            $job = query('job', " id = '$array[realJobId]'");
            $contract = query('staff_contract', "staffId = '$array[stid]'  order by signDate desc");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "department":
                        $row[] = departmentClass::getTypeName($job['departmentId']);
                        break;
                    case "job":
                        $row[] = $job['name'];
                        break;
                    case "birthDay":
                        $row[] =  self::null($array['birthDay']);
                        break;
                    case "contractDate":
                        $row[] =  $contract['signDate'];
                        break;
                    case "insureDate":
                        $staff_insure = query('staff_insure', "staffId = '$array[stid]'");
                        $row[] =  $staff_insure['insureDate'];
                        break;
                    case "endDate":
                        if ($contract['contractLimitType'] == '无固定期限') {
                            $contractLimitType = $contract['contractLimitType'];
                        } else {
                            $contractLimitType = strtotime($contract['signEndDate']) > 0 && strtotime($contract['signEndDate']) < time() ? "<span class='red'>{$contract['signEndDate']}</span>" : self::null($contract['signEndDate']);
                        }
                        $row[] =  $contractLimitType;
                        break;
                    case "state":
                        $row[] =  $array['workFlow'] == '待复核' ? $array['workFlow'] : $array['state'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 100),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function editPage()
    {
        $id = $this->get('id') ?: suiji();
        $staff = query(self::table, " stid = '" . $id . "' ");
        $info = query('talent_pool', " id = '" . $staff['talentId'] . "' ");

        //引入人才库对象
        $talentObj = new talentPoolClass();
        /*****学习经历*********/
        $educationTr[] = [
            "",
            L('staffProfiles.table.study_date'),
            L('staffProfiles.table.university'),
            L('staffProfiles.table.study_major'),
            L('staffProfiles.table.achievements'),
        ];
        $result = find(array(
            'field' => "id as studyId,studyDate as educationDate,college as school,major as schoolMajor,certificate",
            'table' => "study_history where talentId = '{$info['id']}' order by list asc"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $educationTr[] = $talentObj->educationRow($array);
            }
        }else{
            $educationTr[] = $talentObj->educationRow(['studyId'=>self::getId(), 'list'=>1]);
        }

        /*****工作经历*********/
        $workTr[] = [
            "",
            L('staffProfiles.table.work_date_start'),
            L('staffProfiles.table.employed'),
            L('staffProfiles.table.station'),
            L('staffProfiles.table.work_content'),
            L('staffProfiles.table.quit_reason'),
        ];
        $result = find(array(
            'field' => "id as workId,workDate,companyName,position,content,cause",
            'table' => "job_history where talentId = '{$info['id']}' order by list asc"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $workTr[] = $talentObj->workRow($array);
            }
        }else{
            $workTr[] = $talentObj->workRow(['workId'=>self::getId(), 'list'=>1]);
        }

        /*****家庭成员*********/
        $familyTr[] = [
            "",
            L('staffProfiles.table.name'),
            L('staffProfiles.table.relationship'),
            L('staffProfiles.table.work_unit'),
            L('staffProfiles.table.contactTel'),
        ];
        $result = find(array(
            'field' => "id as familyId,name as memberName,relation,company as memberCompany,contactTel",
            'table' => "talent_family where talentId = '{$info['id']}' order by list asc"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $familyTr[] = $talentObj->familyRow($array);
            }
        }else{
            $familyTr[] = $talentObj->familyRow(['familyId'=>self::getId(), 'list'=>1]);
        }

        /*******附件****************/
        //入职信息
        $entry = query('staff_entry_record', " talentId = '$info[id]' and id not in (select entryId from staff_quit_record where isConfirm = 1) order by time desc");
        $button = [];
        if ($this->power(self::page, "edit")) {
            //按钮
            $button[] = [
                "name" => L('staffProfiles.table.save'),
                "type" => "点击事件",
                "cla" => $this->get('cla'),
                "fun" => "subForm('" . self::page . "EditPageForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editPageEdit')",
                "post" => ["id" => $id],
            ];
        }
        $entry['contractLimitType'] = $entry['contractLimitType'] ?: '固定期限';
        $entry['contractYear'] = !$entry['contractYear'] && $entry['contractLimitType'] == '固定期限' ? 3 : $entry['contractYear'];//默认3年
        $job = query('job', "id = '$info[jobId]'");
        $departmentName = departmentClass::getTypeName($job['departmentId']);
        $talentObj = new talentPoolClass();
        $data['name'] = $info['name']?:'新建';
        $data['button'] = $this->tableShowButton($button);
        //表单
        $body = $this->edit4([
            '基本信息' => [
                [
                    L('staffProfiles.table.orderNo') . "：" => text(["name" => "orderNo", "value" => $staff['orderNo']]),
                    must . L('staffProfiles.table.name') . "：" => text(["name" => "name", "value" => $info['name']]),
                    must . L('staffProfiles.table.sex') . "：" => radio(["name" => "sex", 'value' => ['男', '女'], "checked" => $info['sex'] ?: '']),
                    must . L('staffProfiles.table.tel') . "：" => text(["name" => "tel", "value" => $info['tel']]),
                ],
                [
                    must . L('staffProfiles.table.appliedJob') . "：" => selectMultiple([
                        "name" => "jobId", "title" => L('staffProfiles.table.appliedJob'),
                        'value' => $info['jobId'],
                        'sqlField' => 'name',
                        'sqlId' => 'id',
                        'table' => "job",
                    ]),
                    must . L('staffProfiles.table.education') . "：" => select(array('name' => 'education', 'title' => L('staffProfiles.table.education'), 'class' => 'select', 'value' => $info['education'], 'option' => explode('，', para('education')))),
                    L('staffProfiles.table.email') . "：" => text(["name" => "email", "value" => $info['email']]),
//                    L('staffProfiles.table.expect_salary') . "：" => select(array('name' => 'exSalary', 'title' => L('staffProfiles.table.expect_salary'), 'class' => 'select', 'value' => $info['exSalary'], 'option' => explode('，', para('exSalary')))),//期望薪资
                ],
                [
                    L('staffProfiles.table.expect_address') . "：" => select(array('name' => 'exWorkPlace', 'title' => L('staffProfiles.table.expect_address'), 'class' => 'select', 'value' => $info['exWorkPlace'], 'option' => explode('，', para('exWorkPlace')))),
                    must . L('staffProfiles.table.idCard') . "：" => text(["name" => "idCard", 'blur' => 'getBirthDay', "value" => $info['idCard']]),
                    L('staffProfiles.table.nation') . "：" => select(array('name' => 'nation', 'title' => L('staffProfiles.table.nation'), 'class' => 'select', 'value' => $info['nation'], 'option' => explode('、', para('nationOption')))),
                    L('staffProfiles.table.homeTown') . "：" => repeatSelect(array('name' => 'homeTown', 'title' => L('staffProfiles.table.homeTown'), 'sqlForm' => 'region', 'sqlField' => 'province', 'value' => $info['homeTown'])),
                ],
                [
//                    L('staffProfiles.table.height') . "：" => text(["name" => "height", 'unit' => 'cm', "value" => $info['height'] > 0 ? $info['height'] : '']),
//                    L('staffProfiles.table.weight') . "：" => text(["name" => "weight", 'unit' => 'kg', "value" => $info['weight'] > 0 ? $info['weight'] : '']),
                    L('staffProfiles.table.college') . "：" => text(["name" => "college", "value" => $info['college']]),
                    L('staffProfiles.table.major') . "：" => text(["name" => "major", "value" => $info['major']]),
                ],
                [
                    L('staffProfiles.table.workInDate') . "：" => text(["name" => "workInDate", 'laydate' => ['type'=>'year'], "unit" => '年', "value" => $info['workDate']]),
                    L('staffProfiles.table.health') . "：" => select(array('name' => 'health', 'title' => '健康状况', 'class' => 'select', 'value' => $info['health'], 'option' => para('healthOption', '，'))),
                    L('staffProfiles.table.marriage') . "：" => radio(["name" => "marriage", 'value' => $talentObj->marryOption, "checked" => $info['marriage']]),
                    L('staffProfiles.table.politicsStatus') . "：" => select(array('name' => 'politicsStatus', 'title' => L('staffProfiles.table.politicsStatus'), 'class' => 'select', 'value' => $info['politicsStatus'], 'option' => para('politicsStatus', '，'))),
                ],
                [
                    L('staffProfiles.table.residenceAddress') . "：" => text(["name" => "residenceAddress", "value" => $info['residenceAddress']]),
                    L('staffProfiles.table.residenceType') . "：" => radio(["name" => "residenceType", 'value' => $talentObj->residenceTypeOption, "checked" => $info['residenceType']]),
                    L('staffProfiles.table.liveAddress') . "：" => text(["name" => "liveAddress", "value" => $info['liveAddress']]),
                    L('staffProfiles.table.postCode') . "：" => text(["name" => "postCode", "value" => $info['postCode']]),
                ],
                [
                    must . L('staffProfiles.table.secContactName') . "：" => text(["name" => "secContactName", "value" => $info['secContactName']]),
                    must . L('staffProfiles.table.secContactRelation') . "：" => text(["name" => "secContactRelation", "value" => $info['secContactRelation']]),
                    must . L('staffProfiles.table.secContactTel') . "：" => text(["name" => "secContactTel", "value" => $info['secContactTel']]),
                    L('staffProfiles.talentPool.channels') . "：" => select(array('name' => 'sourceType', 'title' => '请选择', 'class' => 'select', 'value' => $info['source'], 'option' => explode('，', para('talentSourceOption')))),
                ],
                [
                    L('staffProfiles.table.text') . "：" => textarea(["name" => "text", "value" => $info['text']]),
                ],
            ],
            L('staffProfiles.detail.work_info') => [
                [
                    must . L('staffProfiles.table.entryDate') . "：" => text(["name" => "entryDate", 'laydate' => [], "value" => $entry['entryDate']]),
                    must . L('staffProfiles.table.tryDate') . "：" => text(["name" => "endDate", 'laydate' => [], "value" => $entry['endDate']]),
                    must . L('staffProfiles.table.contractType') . "：" => radio(["name" => "contractType", 'value' => explode('，', para('contractTypeOption')), "checked" => $entry['contractType'] ?: '劳动合同']),
                    L('staffProfiles.table.superior') . "：" => selectMultiple([
                        "name" => "managerId", "title" => L('staffProfiles.table.superior'),
                        'value' => $entry['managerId'],
                        'sqlField' => 'name',
                        'sqlId' => 'stid',
                        'table' => "staff",
                    ]),
                ],
                [
//                    must . L('staffProfiles.table.insure') . "：" => text(["name" => "insure", "value" => $entry['insure']]),
//                    must . L('staffProfiles.table.workSalary') . "：" => text(["name" => "workSalary", "value" => $entry['workSalary']]),
                    must . L('staffProfiles.table.contractyear') . "：" => radio(array('name' => 'contractLimitType', 'checked' => $entry['contractLimitType'], 'value' => ['固定期限' => '固定期限' . "&nbsp;<input name='contractYear' min='0' style='padding:5px;width: 100px' type='number' value='{$entry['contractYear']}'>&nbsp;月&nbsp;&nbsp;", '无固定期限' => '无固定期限'])),
                ],
                [
                    must . L('staffProfiles.talentPool.beJob') . "：" => selectMultiple([
                        "name" => "jobId", "title" => L('staffProfiles.talentPool.beJob'),
                        'value' => $entry['jobId'],
                        'sqlField' => 'name',
                        'sqlId' => 'id',
                        'table' => "job",
                        'where' => "1=1 order by list",
                        'change' => 'getJobInfo'
                    ]),
                    L('job.table.jobType') . '：' => "<span id='jobType'>{$job['type']}</span>",
                    L('job.table.department_name') . '：' => "<span id='department'>{$departmentName}</span>",
                ],
                [
                    L('staffProfiles.table.work_text') . "：" => textarea(["name" => "workText", "value" => $entry['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'title' => L('staffProfiles.table.learning_experience'),
            'html' => $this->listTable(array('tr' => $educationTr, 'end' => true, 'displayFields' => false)),
        ]);
        $body .= $this->editList([
            'title' => L('staffProfiles.table.work_experience'),
            'html' => $this->listTable(array('tr' => $workTr, 'end' => true, 'displayFields' => false)),
        ]);
        $body .= $this->editList([
            'title' => L('staffProfiles.table.family_member'),
            'html' => $this->listTable(array('tr' => $familyTr, 'end' => true, 'displayFields' => false)),
        ]);
        $body .= $this->editBlock([
            L('staffProfiles.table.enclosure') => fileUploadClass::addFileComponent($id, '人才库', self::page, self::page . 'EditPageForm')
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(array('name' => 'id', 'value' => $id)),
        ]);
        $data['html'] .= $talentObj->editJs();


        //返回
        return $this->tab($data);
    }

    public function editPageEdit()
    {
        $id = $this->post('id');
        $talentPoolField = [
            'state' => '已入职',
            'workFlow' => 2,
            'name' => $this->post('name'),
            'sex' => $this->post('sex'),
            'tel' => $this->post('tel'),
            'idCard' => $this->post('idCard'),
            'birthDay' => $this->post('idCard')?self::getBirthdayFromIDCard($this->post('idCard')):'',
            'nation' => $this->post('nation'),
            'homeTown' => $this->post('homeTown'),
            'height' => $this->post('height'),
            'weight' => $this->post('weight'),
            'health' => $this->post('health'),
            'education' => $this->post('education'),
            'major' => $this->post('major'),
            'college' => $this->post('college'),
            'workDate' => $this->post('workInDate'),
            'marriage' => $this->post('marriage'),
            'politicsStatus' => $this->post('politicsStatus'),
            'residenceAddress' => $this->post('residenceAddress'),
            'liveAddress' => $this->post('liveAddress'),
            'secContactName' => $this->post('secContactName'),
            'secContactTel' => $this->post('secContactTel'),
            'secContactRelation' => $this->post('secContactRelation'),
            'jobTitle' => $this->post('jobTitle'),
            'text' => $this->post('text'),
            'postCode' => $this->post('postCode'),
            'email' => $this->post('email'),
            'source' => $this->post('sourceType'),
            'residenceType' => $this->post('residenceType'),
        ];
        $annotation = [
            'name' => L('staffProfiles.table.name'),
            'sex' => L('staffProfiles.table.sex'),
            'tel' => L('staffProfiles.table.tel'),
            'idCard' => L('staffProfiles.table.idCard'),
            'education' => L('staffProfiles.table.education'),
            'workDate' => L('staffProfiles.table.workInDate'),
            'height' => L('staffProfiles.table.height'),
            'weight' => L('staffProfiles.table.weight'),
            'secContactTel' => L('staffProfiles.table.secContactTel'),
            'secContactName' => L('staffProfiles.table.secContactName'),
            'secContactRelation' => L('staffProfiles.table.secContactRelation'),
        ];
        $rules = [
            'name' => 'required',
            'sex' => 'required',
            'tel' => 'required|tel',
            'idCard' => 'required|id_card',
            'education' => 'required',
            'workDate' => 'numeric|min:1|max:'.date("Y"),
            'height' => 'numeric',
            'weight' => 'numeric',
            'secContactTel' => 'tel',
            'secContactName' => 'required',
            'secContactRelation' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($talentPoolField, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $entryField = [
            'jobId' => $this->post('jobId'),
            'managerId' => $this->post('managerId'),
            'entryDate' => $this->post('entryDate'),
            'endDate' => $this->post('endDate'),
            'text' => $this->post('workText'),
            'contractType' => $this->post('contractType'),
            'contractYear' => $this->post('contractYear'),
            'contractLimitType' => $this->post('contractLimitType'),
            'workSalary' => $this->post('workSalary'),
            'insure' => $this->post('insure'),
        ];
        $enAnnotation = [
            'entryDate' => L('staffProfiles.table.entryDate'),
            'endDate' => L('staffProfiles.table.tryDate'),
            'contractType' => L('staffProfiles.table.contractType'),
            'contractLimitType' => L('staffProfiles.table.contractyear'),
            'insure' => L('staffProfiles.table.insure'),
            'workSalary' => L('staffProfiles.table.workSalary'),
            'jobId' => L('staffProfiles.talentPool.beJob'),
        ];
        $enRules = [
            'entryDate' => 'required',
            'endDate' => 'required',
            'contractType' => 'required',
            'contractLimitType' => 'required',
//            'insure' => 'required',
//            'workSalary' => 'required',
            'jobId' => 'required',
        ];
        // 校验是否符合规则
        $entryResult = $vt->setAliases($enAnnotation)->validate($entryField, $enRules)->isOk();
        if ($entryResult === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //学习经历
        $studyIdArr = $this->post('studyId') ?: [];
        $educationDateArr = $this->post('educationDate');
        $schoolArr = $this->post('school');
        $schoolMajorArr = $this->post('schoolMajor');
        $certificateArr = $this->post('certificate');
        //工作经历
        $workIdArr = $this->post('workId') ?? [];
        $workDateArr = $this->post('workDate');
        $companyNameArr = $this->post('companyName');
        $positionArr = $this->post('position');
        $contentArr = $this->post('content');
        $causeArr = $this->post('cause');
        //家庭成员
        $familyIdArr = $this->post('familyId') ?? [];
        $memberNameArr = $this->post('memberName');
        $relationArr = $this->post('relation');
        $memberCompanyArr = $this->post('memberCompany');
        $contactTelArr = $this->post('contactTel');
        //附件
        $fileIdArr = $this->post('fileId');
        $staff = query(self::table, "stid = '$id'");
        $info = query('talent_pool', "id = '$staff[talentId]'");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('staffProfiles.talentPool.edit_permission');
            //} elseif (!preg_match("/^([\x{4e00}-\x{9fa5}]+)$/u", $talentPoolField['name']) && !preg_match("/^[a-z]+$/i", $talentPoolField['name'])) {
        } elseif (!preg_match("/^[\x{4e00}-\x{9fa5}a-zA-Z0-9]+$/u", $talentPoolField['name'])) {
            $json['warn'] = L('staffProfiles.tip.name_warn');
        } elseif (!empty($field['email']) && preg_match(checkEmail, $talentPoolField['email']) == 0) {
            $json['warn'] = L('staffProfiles.tip.email_warn');
        } elseif (static::total(array('table' => 'talent_pool', 'where' => " and idCard = '{$talentPoolField['idCard']}' and id !='$id'"))) {
            $json['warn'] = L('staffProfiles.tip.idCard_repeat_warn');
        } elseif (!empty($talentPoolField['birthDay']) && $this->age($talentPoolField['birthDay']) < 16) {
            $json['warn'] = L('staffProfiles.tip.age_warn');
        } elseif (empty($id)) {
            $json['warn'] = '未找到ID';
        } else {
            $this->startTrans();//开启事务
            $isPass = true;//事务通过标志
            /*********人才库表信息***********/
            if (empty($info['id'])) {
                $talentPoolField = array_merge($talentPoolField, [
                    'id' => suiji(),
                ]);
                $json['warn'] = static::insert([
                    "table" => 'talent_pool',
                    "field" => $talentPoolField,
                ]);
            } else {
                $json['warn'] = static::update([
                    "table" => 'talent_pool',
                    "field" => $talentPoolField,
                    "where" => "id = '$info[id]'"
                ]);
                $talentPoolField['id'] = $info['id'];
            }

            /*********员工表信息***********/

            if (strtotime($entryField['endDate']) < time()) {
                //试用期小于当前时间
                $state = '转正';
            } else {
                $state = '试用';
            }
            $staffField = [
                'jobId' => $entryField['jobId'],
                'talentId' => $talentPoolField['id'],
                'state' => $state,
                'name' => $talentPoolField['name'],
                'tel' => $talentPoolField['tel'],
                'manager' => $entryField['managerId'],
            ];
            $userNo = codeTemplateClass::generateCode('staffProfiles', [
                'prefix' => 'YM' . date('Ymd'),
                'table' => 'staff',
                'field' => 'orderNo',
                'where' => '',
            ], $staffField);
            if (empty($staff['stid'])) {
                $staffField = array_merge($staffField, [
                    'orderNo' => $this->post('orderNo') ?: $userNo,
                    'ico' => 'img/websiteImg/replaceHead.jpg',
                    'stid' => suiji(),
                    'workFlow' => '待复核'
                ]);
                $warn = static::insert([
                    "table" => self::table,
                    "field" => $staffField,
                ]);
            } else {
                $warn = static::update([
                    "table" => self::table,
                    "field" => $staffField,
                    "where" => "stid = '$staff[stid]'"
                ]);
                $staffField['stid'] = $staff['stid'];
            }
            if (!in_array($warn, ['新增成功', '更新成功'])) {
                $json['warn'] = $warn;
            }

            /******入职记录信息*******/
            $entryRecord = query('staff_entry_record', " talentId = '$talentPoolField[id]' and id not in (select entryId from staff_quit_record where isConfirm = 1) order by time desc");
            if (!empty($entryRecord['id'])) {
                //更新
                $warn = static::update(array('table' => 'staff_entry_record', 'field' => $entryField, 'where' => " id ='$entryRecord[id]'"));
            } else {
                //新增
                $userNo = codeTemplateClass::generateCode('staffEntryRecord', [
                    'prefix' => 'RZSQ' . date('Ymd'),
                    'table' => 'staff_entry_record',
                    'field' => 'orderNo',
                    'where' => '',
                ], $entryField);
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $staffEntryRecordId = self::getId();
                $entryField = array_merge($entryField, [
                    'id' => $staffEntryRecordId,
                    'orderNo' => $userNo,
                    'deptName' => $department['name'],
                    'time' => $this->time,
                    'state' => '已通过',
                    'stid' => $this->control['stid'],
                    'talentId' => $talentPoolField['id'],
                ]);
                $warn = static::insert(array('table' => 'staff_entry_record', 'field' => $entryField));
                $entryRecord['id'] = $staffEntryRecordId;
            }
            if (!in_array($warn, ['新增成功', '更新成功'])) {
                $json['warn'] = $warn;
            }
            //添加或更新学习经历
            if (is_array($studyIdArr)) {
                foreach ($studyIdArr as $k => $nid) {
                    $studyField = [
                        'studyDate' => $educationDateArr[$k],
                        'college' => $schoolArr[$k],
                        'major' => $schoolMajorArr[$k],
                        'certificate' => $certificateArr[$k],
                    ];
                    $exist = static::total(array('table' => 'study_history', 'where' => " and id = '$nid'"));
                    if(empty(array_filter($studyField, 'strlen'))) {
                        if ($exist > 0) delete(array('table' => 'study_history', 'where' => " id = '$nid' "));
                        continue;
                    }
                    if ($exist > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'study_history',
                            "field" => $studyField,
                            "where" => " id = '$nid'",
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'study_history',
                            "field" => array_merge($studyField, [
                                'id'       => $nid,
                                'talentId' => $id,
                                'time'     => $this->time,
                            ]),
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加或更新工作经历
            if (is_array($workIdArr)) {
                foreach ($workIdArr as $k => $nid) {
                    $workField = [
                        'companyName' => $companyNameArr[$k],
                        'position' => $positionArr[$k],
                        'content' => $contentArr[$k],
                        'cause' => $causeArr[$k],
                        'workDate' => $workDateArr[$k],
                    ];
                    $exist = static::total(array('table' => 'job_history', 'where' => " and id = '$nid'"));
                    if(empty(array_filter($workField, 'strlen'))) {
                        if ($exist > 0) delete(array('table' => 'job_history', 'where' => " id = '$nid' "));
                        continue;
                    }
                    if ($exist > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'job_history',
                            "field" => $workField,
                            "where" => " id = '$nid'",
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'job_history',
                            "field" => array_merge($workField, [
                                'id'       => $nid,
                                'talentId' => $id,
                                'time'     => $this->time,
                            ]),
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加或更新家庭成员
            if (is_array($familyIdArr)) {
                foreach ($familyIdArr as $k => $nid) {
                    $familyField = [
                        'name' => $memberNameArr[$k],
                        'relation' => $relationArr[$k],
                        'company' => $memberCompanyArr[$k],
                        'contactTel' => $contactTelArr[$k],
                    ];
                    $exist = static::total(array('table' => 'talent_family', 'where' => " and id = '$nid'"));
                    if(empty(array_filter($familyField, 'strlen'))) {
                        if ($exist > 0) delete(array('table' => 'talent_family', 'where' => " id = '$nid' "));
                        continue;
                    }
                    if ($exist > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'talent_family',
                            "field" => $familyField,
                            "where" => " id = '$nid'",
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'talent_family',
                            "field" => array_merge($familyField, [
                                'id'       => $nid,
                                'talentId' => $id,
                                'time'     => $this->time,
                            ]),
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加主表ID到附件表
            if (is_array($fileIdArr)) {
                $warn = update(array('table' => 'file', 'field' => ['targetId' => $talentPoolField['id']], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                if ($warn != '更新成功') {
                    $json['warn'] = $warn;
                }
            }
            if ($isPass && in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();//提交事务
                //删除不在此ID中的数据
                delete(array('table' => 'talent_family', 'where' => " id not in ('" . implode("','", $familyIdArr) . "') and talentId = '$talentPoolField[id]'"));
                delete(array('table' => 'job_history', 'where' => " id not in ('" . implode("','", $workIdArr) . "') and talentId = '$talentPoolField[id]'"));
                delete(array('table' => 'study_history', 'where' => " id not in ('" . implode("','", $studyIdArr) . "') and talentId = '$talentPoolField[id]'"));
                $staff_entry_record = query('staff_entry_record', "id = '$entryRecord[id]'");

                $staffEntry = new staffEntryRecordClass();
                //生成合同
                $staffEntry->insertContract($staffField['stid'], $staff_entry_record, '员工新增');
                //生成社会保险
                $staffEntry->insertInsure($staffField['stid'], $staff_entry_record, '员工新增');

                //生成转正记录
                $staff = query('staff', "stid = '$staffField[stid]'");
                if ($staff['state'] == '转正') {
                    $this->creatFormaRecord($staff_entry_record, $staffField['stid']);//试用结束日期当做转正日期
                }
                $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $staffField['stid'];
                //添加日志
                $text = $this->control['name'] . "新增了员工【$talentPoolField[name]】";
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = $url;
            } else {
                $this->rollback();//回滚
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 复核
     */
    public function review(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    L('staffProfiles.tip.review_key') . "：" => L('staffProfiles.tip.review_title'),
                ),
            ),
        ));
        //返回
        return $this->layer(array("title" => L('staffProfiles.button.review'), "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 复核
     */
    public function reviewEdit(): bool|string
    {
        $idArr = $this->post('listId');
        if (static::is_null_array($idArr)) {
            $all = find(array('table' => self::table, 'where' => "worKFlow = '待复核'"));
            foreach ($all['array'] as $array) {
                $idArr[] = $array['stid'];
            }
        }
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('staffProfiles.tip.permission_edit_warn');
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = L('staffProfiles.tip.no_check_data');
        } else {
            $field = [
                'workFlow' => '已复核',
            ];
            $x = 0;
            //存货库存有余额时可以停用
            $warn = '';
            foreach ($idArr as $k => $staffId) {
                $staff = query("staff", " stid = '$staffId' ");
                if ($staff['workFlow'] == '待复核') {
                    $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " stid = '$staffId'"));
                    if ($json['warn'] == '更新成功') {
                        $x++;
                        $warn .= str_replace(['{{staffName}}'], [$staff['name']], L('staffProfiles.other.check_staff_text')) . "<br>";
                    } else {
                        $warn .= str_replace(['{{staffName}}'], [$staff['name']], L('staffProfiles.other.check_staff_text_failed')) . "<br>";
                    }
                }
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('staffProfiles.other.check_staff_log'));
            $this->logText(["type" => self::page, "text" => $text]);
            //返回
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('staffProfiles.other.check_staff_msg'));
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = L('staffProfiles.other.permission_import_warn');
        }else {
            $talent = new talentPoolClass();
            $exampleData[] = [
                'YM202101010001', '张三(示例数据)', '男', '13000000000', '55142319880304500X', '本科', 'J0001', '总经理', '2021-01-01', '2021-01-01', '1', '1000', '固定期限', '36', '', '',
                '重庆大学', '123@mail.com', '重庆市', '5000-8000', '1995-01-01', '汉族', '重庆市', '170', '60', '健康', '计算机', '经济师', '2012-01-01', '未婚', '群众', '重庆市', '非农户口', '重庆市', '400000',
                '张五', '兄弟', '13111111111', '', '', '', '',
            ];
            $columns = $this->getAllColumns();
            $excel    = $this->excelHead();
            $fileName = '员工档案导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $validation = new \Vtiful\Kernel\Validation();
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '员工编号'=>$example[0],
                            '姓名'=>$example[1],
                            '性别'=>$example[2],
                            '手机号码'=>$example[3],
                            '身份证号'=>$example[4],
                            '学历'=>$example[5],
                            '职位编码'=>$example[6],
                            '职位名称'=>$example[7],
                            '入职日期'=>$example[8],
                            '试用期至'=>$example[9],
                            '劳动报酬'=>$example[10],
                            '社会保险'=>$example[11],
                            '合同期限类型'=>$example[12],
                            '合同期限'=>$example[13],
                            '直属上级名称'=>$example[14],
                            '直属上级编号'=>$example[15],
                            '毕业院校'=>$example[16],
                            '邮箱'=>$example[17],
                            '期望工作地点'=>$example[18],
                            '期望薪资'=>$example[19],
                            '出生年月'=>$example[20],
                            '民族'=>$example[21],
                            '籍贯'=>$example[22],
                            '身高'=>$example[23],
                            '体重'=>$example[24],
                            '健康状况'=>$example[25],
                            '专业'=>$example[26],
                            '职称'=>$example[27],
                            '参加工作'=>$example[28],
                            '婚姻状况'=>$example[29],
                            '政治面貌'=>$example[30],
                            '户籍地址'=>$example[31],
                            '户口性质'=>$example[32],
                            '通讯住址'=>$example[33],
                            '邮政编码'=>$example[34],
                            '紧急联系人姓名'=>$example[35],
                            '与紧急联系人关系'=>$example[36],
                            '紧急联系人手机号'=>$example[37],
                            '竞业禁止协议'=>$example[38],
                            '备注'=>$example[39],
                            '工作备注'=>$example[40],
                            '转正日期'=>$example[41],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                        switch ($array['columnName']){
                            case '户口性质':
                                //下拉列表
                                $validation->validationType(\Vtiful\Kernel\Validation::TYPE_LIST)
                                    ->valueList($talent->residenceTypeOption);
                                $filePath = $filePath->validation($columns[$index].($y+2), $validation->toResource());
                                break;
                            case '政治面貌':
                                //下拉列表
                                $validation->validationType(\Vtiful\Kernel\Validation::TYPE_LIST)
                                    ->valueList(para('politicsStatus', '，'));
                                $filePath = $filePath->validation($columns[$index].($y+2), $validation->toResource());
                                break;
                            case '健康状况':
                                //下拉列表
                                $validation->validationType(\Vtiful\Kernel\Validation::TYPE_LIST)
                                    ->valueList(para('healthOption', '，'));
                                $filePath = $filePath->validation($columns[$index].($y+2), $validation->toResource());
                                break;
                            case '婚姻状况':
                                //下拉列表
                                $validation->validationType(\Vtiful\Kernel\Validation::TYPE_LIST)
                                    ->valueList($talent->marryOption);
                                $filePath = $filePath->validation($columns[$index].($y+2), $validation->toResource());
                                break;
                            case '学历':
                                //下拉列表
                                $validation->validationType(\Vtiful\Kernel\Validation::TYPE_LIST)
                                    ->valueList(para('education', '，'));
                                $filePath = $filePath->validation($columns[$index].($y+2), $validation->toResource());
                                break;
                            case '合同期限类型':
                                //下拉列表
                                $validation->validationType(\Vtiful\Kernel\Validation::TYPE_LIST)
                                    ->valueList(['固定期限', '无固定期限']);
                                $filePath = $filePath->validation($columns[$index].($y+2), $validation->toResource());
                                break;
                            case '性别':
                                //下拉列表
                                $validation->validationType(\Vtiful\Kernel\Validation::TYPE_LIST)
                                    ->valueList(['男', '女']);
                                $filePath = $filePath->validation($columns[$index].($y+2), $validation->toResource());
                                break;
                        }
                    }
                    $index++;
                }
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('staffProfiles.other.staff_import_log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /*数据导入分析*/
    public function import()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = L('staffProfiles.tip.permission_import_warn');
        }  else {
            $talent = new talentPoolClass();

            $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list = 0;
            $staffEntry = new staffEntryRecordClass();
            $contractTypeOption = para('contractTypeOption', '，');
            $education = para('education', '，');
            $nationOption = para('nationOption', '、');
            $healthOption = para('healthOption', '，');
            $jobTitleOption = para('jobTitleOption', '，');
            $politicsStatus = para('politicsStatus', '，');
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $cell['入职日期'] = self::importDateFormat($cell['入职日期']);     //入职日期
                    $cell['试用期至'] = self::importDateFormat($cell['试用期至']);     //试用期
                    $cell['出生年月'] = self::importDateFormat($cell['出生年月']);    //出生年月
                    $cell['转正日期'] = self::importDateFormat($cell['转正日期']);    //转正日期
                    $job = query('job', " orderNo = '$cell[职位编码]'");//工作岗位
                    $manager = query('staff', "orderNo = '$cell[直属上级编号]'");
                    $field = [
                        'state' => '已入职',
                        'workFlow' => 2,
                        'name' => $cell['姓名'],
                        'sex' => $cell['性别'],
                        'tel' => $cell['手机号码'],
                        'idCard' => $cell['身份证号'],
                        'education' => $cell['学历'],
                        'jobId' => $job['id'],
                        'college' => $cell['毕业院校'],
                        'email' => $cell['邮箱'],
                        'exWorkPlace' => $cell['期望工作地点'],
                        'exSalary' => $cell['期望薪资'],
                        'birthDay' => $cell['出生年月'],
                        'nation' => $cell['民族'],
                        'homeTown' => $cell['籍贯'],
                        'height' => $cell['身高'],
                        'weight' => $cell['体重'],
                        'health' => $cell['健康状况'],
                        'major' => $cell['专业'],
                        'jobTitle' => $cell['职称'],
                        'workDate' => $cell['参加工作时间'],
                        'marriage' => $cell['婚姻状况'],
                        'politicsStatus' => $cell['政治面貌'],
                        'residenceAddress' => $cell['户籍地址'],
                        'residenceType' => $cell['户口性质'],
                        'liveAddress' => $cell['通讯住址'],
                        'postCode' => $cell['邮政编码'],
                        'secContactName' => $cell['紧急联系人姓名'],
                        'secContactRelation' => $cell['与紧急联系人关系'],
                        'secContactTel' => $cell['紧急联系人手机号'],
                        'isProhibition' => $cell['竞业禁止协议'] ?: '无',
                        'text' => $cell['备注'],
                    ];
                    $annotation = [
                        'name' => L('staffProfiles.table.name'),
                        'sex' => L('staffProfiles.table.sex'),
                        'tel' => L('staffProfiles.table.tel'),
                        'jobId' => L('staffProfiles.table.job'),
                    ];
                    $rules = [
                        'name' => 'required',
                        'sex' => 'required',
                        'tel' => 'required|tel',
                        'jobId' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    $entryField = [
                        'jobId' => $job['id'],
                        'managerId' => $manager['stid'],
                        'entryDate' => $cell['入职日期'],
                        'endDate' => $cell['试用期至'],
                        'text' => $cell['工作备注'],
                        'contractType' => '劳动合同',
                        'contractYear' => $cell['合同期限类型'] == '固定期限' ? $cell['合同期限'] : 0,
                        'contractLimitType' => $cell['合同期限类型'] ?: '无固定期限',
                        'workSalary' => $cell['劳动报酬'],
                        'insure' => $cell['社会保险'] ?: '无',
                    ];
                    $enAnnotation = [
                        'jobId' => L('staffProfiles.table.job'),
                        'entryDate' => L('staffProfiles.table.entryDate'),
                        'endDate' => L('staffProfiles.table.tryDate'),
                        'contractType' => L('staffProfiles.table.contractType'),
                        'contractLimitType' => L('staffProfiles.table.contractyear'),
                        'workSalary' => L('staffProfiles.table.workSalary'),
                        'insure' => L('staffProfiles.table.insure'),
                    ];
                    $enRules = [
                        'jobId' => 'required',
                        'entryDate' => 'required',
                        'endDate' => 'required',
                        'contractType' => 'required',
                        'contractLimitType' => 'required',
                        'workSalary' => 'required',
                        'insure' => 'required',
                    ];
                    $talentPool = query('talent_pool', "idCard = '$field[idCard]'");
                    $staff = query(self::table, "talentId = '$talentPool[id]'");
                    // 校验是否符合规则
                    $vt2 = new \verify();
                    $entryResult = $vt2->setAliases($enAnnotation)->validate($entryField, $enRules)->isOk();
                    $line = str_replace(['{{i}}'], [$row_list], L('job.other.line'));
                    if (empty($job['id'])) {
                        $text .= $line . "：" . L('staffProfiles.other.codeToJob') . "<br>";  // 多个规则提示最前面一条
                    } elseif ($result === false) {
                        $text .= $line . "：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    } elseif ($entryResult === false) {
                        $text .= $line . "：" . $vt2->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    } elseif (empty($field['idCard'])) {//&& (static::total(array('sql' => "SELECT count(*) AS total FROM talent_pool where idCard = '{$field['idCard']}' and id !='$field[id]'"))) > 0
                        $text .= $line . "：" . L('staffProfiles.tip.idCard_repeat_warn') . "<br>";
                    } elseif (!empty($field['birthDay']) && strtotime($field['birthDay']) === false) {
                        $text .= $line . "：" . L('staffProfiles.other.birthDayError') . "<br>";
                    } elseif (!empty($field['birthDay']) && $this->age($field['birthDay']) < 16) {
                        $text .= $line . "：" . L('staffProfiles.tip.age_warn') . "<br>";
                    } elseif (!empty($entryField['contractType']) && !in_array($entryField['contractType'], $contractTypeOption)) {
                        $text .= $line . "：" . L('staffProfiles.other.contractType_range') . "<br>";
                    } elseif (!empty($entryField['contractLimitType']) && !in_array($entryField['contractLimitType'], workContractClass::contractLimitType)) {
                        $text .= $line . "：" . L('staffProfiles.other.contractYear_range') . "<br>";
                    } elseif ($entryField['contractLimitType'] == '固定期限' && preg_match(checkInteger, $entryField['contractYear']) == 0) {
                        $text .= $line . "：" . L('staffProfiles.other.contractYear_limit') . "<br>";
                    } elseif ($entryField['contractYear'] > 100) {
                        $text .= $line . "：" . L('staffProfiles.other.contractYear_transfinite') . "<br>";
                    } elseif (!empty($field['education']) && !in_array($field['education'], $education)) {
                        $text .= $line . "：" . L('staffProfiles.other.education_range') . "<br>";
                    } elseif (!empty($field['nation']) && !in_array($field['nation'], $nationOption)) {
                        $text .= $line . "：" . L('staffProfiles.other.nation_range') . "<br>";
                    } elseif (!empty($field['health']) && !in_array($field['health'], $healthOption)) {
                        $text .= $line . "：" . L('staffProfiles.other.health_range') . "<br>";
                    } elseif (!empty($field['jobTitle']) && !in_array($field['jobTitle'], $jobTitleOption)) {
                        $text .= $line . "：" . L('staffProfiles.other.jobTitle_range') . "<br>";
                    } elseif (!empty($field['politicsStatus']) && !in_array($field['politicsStatus'], $politicsStatus)) {
                        $text .= $line . "：" . L('staffProfiles.other.politicsStatus_range') . "<br>";
                    } elseif (!empty($field['residenceType']) && !in_array($field['residenceType'], $talent->residenceTypeOption)) {
                        $text .= $line . "：" . L('staffProfiles.other.residenceType_range') . "<br>";
                    } elseif (!empty($manager['stid']) && $manager['stid'] == $staff['stid']) {
                        $text .= $line . "：" . L('staffProfiles.other.managerRepeat') . "<br>";
                    } else {
                        if (empty($talentPool['id'])) {
                            $field = array_merge($field, [
                                'id' => suiji(),
                            ]);
                            $warn = static::insert(["table" => 'talent_pool', "field" => $field]);
                        } else {
                            $warn = static::update(["table" => 'talent_pool', "field" => $field, 'where' => "id = '$talentPool[id]'"]);
                            $field['id'] = $talentPool['id'];
                        }
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $entryRecord = query('staff_entry_record', "talentId = '$field[id]' and id not in (select entryId from staff_quit_record where isConfirm = 1)");

                            if (empty($entryRecord['id'])) {
                                //新增入职记录
                                $userNo = codeTemplateClass::generateCode('staffEntryRecord', [
                                    'prefix' => 'RZSQ' . date('Ymd'),
                                    'table' => 'staff_entry_record',
                                    'field' => 'orderNo',
                                    'where' => '',
                                ], []);
                                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                                $entryField = array_merge($entryField, [
                                    'id' => suiji(),
                                    'orderNo' => $userNo,
                                    'deptName' => $department['name'],
                                    'time' => $this->time,
                                    'state' => '已通过',
                                    'stid' => $this->control['stid'],
                                    'talentId' => $field['id'],
                                ]);
                                $entryWarn = static::insert(array('table' => 'staff_entry_record', 'field' => $entryField));
                            } else {
                                $entryField = array_merge($entryField, [
                                    'talentId' => $field['id'],
                                ]);
                                $entryWarn = static::update(array('table' => 'staff_entry_record', 'field' => $entryField, 'where' => "id = '$entryRecord[id]'"));
                                $entryField['id'] = $entryRecord['id'];
                            }
                            if (!in_array($entryWarn, ["新增成功", "更新成功"])) $text .= $line . "：" . $entryWarn . "<br>";
                            $staff_entry_record = query('staff_entry_record', "id = '$entryField[id]'");
                            //新增员工
                            $stid = $staff_entry_record['id'] ? $staffEntry->insertStaff($staff_entry_record, '待复核', $cell['员工编号']) : '';
                            if ($stid && $staff_entry_record['id']) {
                                $x++;
                                //生成合同
                                $staffEntry->insertContract($stid, $staff_entry_record, '导入');
                                //生成社会保险
                                $staffEntry->insertInsure($stid, $staff_entry_record, '导入');
                                //生成转正记录
                                $staff = query('staff', "stid = '$stid'");
                                if ($staff['state'] == '转正') {
                                    $staff_entry_record['formalDate'] = $cell['转正日期'];
                                    $this->creatFormaRecord($staff_entry_record, $stid);
                                }

                                $text .= $line . "：" . L('job.other.import_success') . "<br>";
                            } else {
                                delete(array('table' => 'talent_pool', 'where' => "id = '$field[id]'"));
                                delete(array('table' => 'staff_entry_record', 'where' => "talentId = '$field[id]'"));
                                $text .= $line . "：" . L('job.other.import_failed') . "<br>";
                            }
                        } else {
                            $text .= $line . "：" . L('job.other.import_failed') . "<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = str_replace(['{{staffName}}', '{{fileName}}'], [$this->control['name'], $_FILES['file']['name']], L('job.other.import_log')) . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 生成转正记录
     * @param $info
     * @param $stid
     * @return bool|string
     */
    public function creatFormaRecord($info, $stid)
    {
        $info['formalDate'] = $info['formalDate'] ?? $info['endDate'];
        $staff_formal = query('staff_formal', "staffId = '$stid' and confirmDate = '$info[formalDate]'");
        $field = [
            'jobId' => $info['jobId'],
            'talentId' => $info['talentId'],
            'staffId' => $stid,
            'formalDate' => $info['formalDate'],
            'confirmDate' => $info['formalDate'],
            'deptName' => departmentClass::getTypeName($this->controlJob['departmentId']),
            'stid' => $this->control['stid'],
            'text' => '员工导入自动生成',
            'state' => '已通过',
        ];
        if (!empty($staff_formal['id'])) {
            $warn = self::update(['table' => 'staff_formal', 'field' => $field, 'where' => "id = '$staff_formal[id]'"]);
        } else {
            $field['id'] = suiji();
            $userNo = codeTemplateClass::generateCode(self::page, [
                'prefix' => 'ZZSQ' . date('Ymd'),
                'table' => self::table,
                'field' => 'orderNo',
                'where' => '',
            ], $field);
            $field['orderNo'] = $userNo;
            $warn = self::insert(['table' => 'staff_formal', 'field' => $field]);
        }
        if (!in_array($warn, ['新增成功', '更新成功'])) {
            return $warn;
        }
        return true;
    }

    /**
     * 根据生日计算年龄
     *
     * @param $birthday
     * @return false|int|string
     */
    public function age($birthday)
    {
        $age = strtotime($birthday);
        if ($age === false || $birthday == '0000-00-00' || $birthday == '0100-01-01' || empty($birthday)) {
            return false;
        }
        list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
        $now = strtotime("now");
        list($y2, $m2, $d2) = explode("-", date("Y-m-d", $now));
        $age = $y2 - $y1;
        if ((int)($m2 . $d2) < (int)($m1 . $d1))
            $age -= 1;
        return $age;
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('staffProfiles.tip.permission_export_warn');
        }  else {
            $data = [];
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    'field' => " ta.*,re.entryDate,st.stid,st.jobId as realJobId,st.state,st.orderNo as stNo,st.name,st.manager,st.workFlow",
                    "table" => self::table . " as st left join talent_pool as ta on st.talentId = ta.id left join staff_entry_record as re on (re.talentId = st.talentId and re.id not in (select entryId from staff_quit_record where isConfirm = 1))",
                    "where" => "st.stid in ('".implode("','", $checkedId)."') order by entryDate desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            foreach ($result as $array){
                $realJob = query("job", " id = '$array[realJobId]' ");
                $entryRecord = query('staff_entry_record', " talentId = '$array[id]' order by time desc");
                $manager = query("staff", " stid = '$array[manager]'");
                $operate_credentials = find(array(
                    'field' => "name",
                    'table' => "operate_credentials where talentId = '{$array['id']}'"
                ));
                $operate_credentials = implode(',',array_column($operate_credentials,'name'));
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '员工编号'=>$array['stNo'],
                            '姓名'=>$array['name'],
                            '性别'=>$array['sex'],
                            '手机号码'=>$array['tel'],
                            '职位'=>$realJob['name'],
                            '直属上级'=>$manager['name'],
                            '入职日期'=>$entryRecord['entryDate'],
                            '试用期至'=>$entryRecord['endDate'],
                            '期望工作地点'=>$array['exWorkPlace'],
                            '期望薪资'=>$array['exSalary'],
                            '身份证号'=>$array['idCard'],
                            '出生年月'=>$array['birthDay'],
                            '民族'=>$array['nation'],
                            '籍贯'=>$array['homeTown'],
                            '邮箱'=>$array['email'],
                            '身高'=>$array['height'],
                            '体重'=>$array['weight'],
                            '健康状况'=>$array['health'],
                            '学历'=>$array['education'],
                            '专业'=>$array['major'],
                            '毕业院校'=>$array['college'],
                            '参加工作时间'=>$array['workDate'],
                            '婚姻状况'=>$array['marriage'],
                            '政治面貌'=>$array['politicsStatus'],
                            '邮政编码'=>$array['postCode'],
                            '户籍地址'=>$array['residenceAddress'],
                            '户口性质'=>$array['residenceType'],
                            '通讯住址'=>$array['liveAddress'],
                            '紧急联系人姓名'=>$array['secContactName'],
                            '与紧急联系人关系'=>$array['secContactRelation'],
                            '紧急联系人手机号'=>$array['secContactTel'],
                            '竞业禁止协议'=>$array['isProhibition'],
                            '合同期限'=>self::null($array['insureDate']),
                            '操作证书'=>$operate_credentials,
                            '备注'=>$array['text'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('staffProfiles.other.export_log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('staffProfiles.table.staffForm') . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /**
     * 入职页
     *
     * @return string
     */
    public function entry(): string
    {
        $staff = query(self::table, " stid = '" . $this->get('id') . "' ");
        $info = query('talent_pool', " id = '" . $staff['talentId'] . "' ");

        //引入人才库对象
        $talentObj = new talentPoolClass();
        /*****学习经历*********/
        $educationTr[] = [
            "",
            L('staffProfiles.table.study_date'),
            L('staffProfiles.table.university'),
            L('staffProfiles.table.study_major'),
            L('staffProfiles.table.achievements'),
        ];
        $result = find(array(
            'field' => "id as studyId,studyDate as educationDate,college as school,major as schoolMajor,certificate",
            'table' => "study_history where talentId = '{$info['id']}' order by list asc"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $educationTr[] = $talentObj->educationRow($array);
            }
        }else{
            $educationTr[] = $talentObj->educationRow(['studyId'=>self::getId(), 'list'=>1]);
        }

        /*****工作经历*********/
        $workTr[] = [
            "",
            L('staffProfiles.table.work_date_start'),
            L('staffProfiles.table.employed'),
            L('staffProfiles.table.station'),
            L('staffProfiles.table.work_content'),
            L('staffProfiles.table.quit_reason'),
        ];
        $result = find(array(
            'field' => "id as workId,workDate,companyName,position,content,cause",
            'table' => "job_history where talentId = '{$info['id']}' order by list asc"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $workTr[] = $talentObj->workRow($array);
            }
        }else{
            $workTr[] = $talentObj->workRow(['workId'=>self::getId(), 'list'=>1]);
        }

        /*****家庭成员*********/
        $familyTr[] = [
            "",
            L('staffProfiles.table.name'),
            L('staffProfiles.table.relationship'),
            L('staffProfiles.table.work_unit'),
            L('staffProfiles.table.contactTel'),
        ];
        $result = find(array(
            'field' => "id as familyId,name as memberName,relation,company as memberCompany,contactTel",
            'table' => "talent_family where talentId = '{$info['id']}' order by list asc"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $familyTr[] = $talentObj->familyRow($array);
            }
        }else{
            $familyTr[] = $talentObj->familyRow(['familyId'=>self::getId(), 'list'=>1]);
        }

        /*****操作证书*********/
        $credentialsTr[] = [
            "",
            L('staffProfiles.table.operate_credentials'),
            L('staffProfiles.table.credentialsDueDate'),
            L('staffProfiles.table.credentialsUploadDate'),
        ];
        $result = find(array(
            'field' => "id as credentialsId,type,startDate,isLong,name,endDate,orderNo,official,auditDate,remindStid,limitDay,text,time",
            'table' => "operate_credentials where talentId = '{$info['id']}'"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $liButton = "";
                $fileId = "";
                $fileIdArr = find(['table'=>'file','where'=>"targetId='{$array['credentialsId']}'"]);
                if(!empty($fileIdArr['array'])){
                    foreach ($fileIdArr['array'] as $item){
                        $dominate = array(
                            "download" => array("name" => $item['name'], "href" => $item['src']),
                        );
                        if (in_array($item['format'], array("doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"))) {
                            $dominate['preview'] = array("format" => $item['format'], "name" => $item['name'], "href" => $item['src']);
                        } elseif (in_array($item['format'], array("png", "gif", "jpg"))) {
                            $dominate['img'] = array("title" => "在线预览", "href" => $item['src']);
                        }
                        $liButton .= $item['name'].$this->dominate($dominate);
                    }
                    $fileId = array_column($fileIdArr['array'],'id');
                    $fileId = implode(',', $fileId);
                }
                $credentialsTr[] = [
                    componentClass::tablePperation('1', "credentialsDelRow(this)",'','',"layer(\"staffProfiles\",\"credentialsEdit\",{talentId:\"{$staff['stid']}\",id:\"{$array['credentialsId']}\"})"),
                    hidden(array('name' => 'operateCredentialsId[]', 'value' => $array['credentialsId'])) .
                    hidden(array('name' => 'operateCredentialstype[]', 'value' => $array['type'])) .
                    hidden(array('name' => 'operateCredentialsstartDate[]', 'value' => $array['startDate'])) .
                    hidden(array('name' => 'operateCredentialsisLong[]', 'value' => $array['isLong'])) .
                    hidden(array('name' => 'operateCredentialsname[]', 'value' => $array['name'])) .
                    hidden(array('name' => 'operateCredentialsorderNo[]', 'value' => $array['orderNo'])) .
                    hidden(array('name' => 'operateCredentialsofficial[]', 'value' => $array['official'])) .
                    hidden(array('name' => 'operateCredentialsauditDate[]', 'value' => $array['auditDate'])) .
                    hidden(array('name' => 'operateCredentialsremindStid[]', 'value' => $array['remindStid'])) .
                    hidden(array('name' => 'operateCredentialslimitDay[]', 'value' => $array['limitDay'])) .
                    hidden(array('name' => 'operateCredentialstext[]', 'value' => $array['text'])) .
                    hidden(array('name' => 'operateCredentialsendDate[]', 'value' => $array['endDate'])) .
                    hidden(array('name' => 'operateCredentialstime[]', 'value' => $array['time'])) .
                    hidden(array('name' => 'operateCredentialsfileId[]', 'value' => $fileId)) .
                    $liButton,
                    $array['isLong'] == 1 ? '永久' : $array['endDate'],
                    $array['time'],
                ];
            }
        }

        $button = $photo = [];
        if ($this->power(self::page, "edit")) {
            //按钮
            $button[] = [
                "name" => L('public.save'),
                "type" => "点击事件",
                "cla" => $this->get('cla'),
                "fun" => "subForm('" . self::page . "EntryForm', root+'control/adIndex.html?cla=" . self::page . "&fun=entryEdit')",
                "post" => ["id" => $this->get('id')],
                'style' => 'li-btn-blue-bg',
            ];

            $ico = [];
            $all = find(array('table' => 'file', 'where' => "targetId = '$info[id]' and target in ('入职登记表','身份证正面','身份证背面','毕业证','学位证','银行卡','离职证明','体检报告','职称证书','竞业限制协议')"));
            foreach ($all['array'] as $array) {
                $ico[$array['target']] = ['id' => $array['id'], 'src' => $array['src']];
            }
            $photo = array(
                array("title" => L('staffProfiles.table.front_of_id_card'), 'type' => '身份证正面', "url" => $ico['身份证正面']['src'] ?? '', "fileId" => $ico['身份证正面']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.back_of_id_card'), 'type' => '身份证背面', "url" => $ico['身份证背面']['src'] ?? '', "fileId" => $ico['身份证背面']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.diploma'), 'type' => '毕业证', "url" => $ico['毕业证']['src'] ?? '', "fileId" => $ico['毕业证']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.degree_diploma'), 'type' => '学位证', "url" => $ico['学位证']['src'] ?? '', "fileId" => $ico['学位证']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.bank_card'), 'type' => '银行卡', "url" => $ico['银行卡']['src'] ?? '', "fileId" => $ico['银行卡']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.registration_form'), 'type' => '入职登记表', "url" => $ico['入职登记表']['src'] ?? '', "fileId" => $ico['入职登记表']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.leaving_certificate'), 'type' => '离职证明', "url" => $ico['离职证明']['src'] ?? '', "fileId" => $ico['离职证明']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.medical_report'), 'type' => '体检报告', "url" => $ico['体检报告']['src'] ?? '', "fileId" => $ico['体检报告']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.Professional_certificate'), 'type' => '职称证书', "url" => $ico['职称证书']['src'] ?? '', "fileId" => $ico['职称证书']['id'] ?? '', "id" => $info['id']),
                array("title" => L('staffProfiles.table.competition_agreement'), 'type' => '竞业限制协议', "url" => $ico['竞业限制协议']['src'] ?? '', "fileId" => $ico['竞业限制协议']['id'] ?? '', "id" => $info['id']),
            );
        }

        //表单
        $data['name'] = $info['name'];
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    L('staffProfiles.table.orderNo') . "：" => text(["name" => "orderNo", "value" => $staff['orderNo']]),
                    must . L('staffProfiles.table.name') . "：" => text(["name" => "name", "value" => $info['name']]),
                    must . L('staffProfiles.table.sex') . "：" => radio(["name" => "sex", 'value' => $this->sexOption, "checked" => $info['sex']]),
                    must . L('staffProfiles.table.tel') . "：" => text(["name" => "tel", "value" => $info['tel']]),
                ],
                [
                    L('staffProfiles.table.superior') . "：" => selectMultiple(array('name' => 'manager', 'title' => L('staffProfiles.table.superior'), 'value' => $staff['manager'], 'table' => 'staff', 'sqlId' => 'stid', 'sqlField' => 'name', 'where' => "workFlow='已复核' and state !='离职' order by orderNo asc")),
                    L('staffProfiles.table.email') . "：" => text(["name" => "email", "value" => $info['email']]),
                    must . L('staffProfiles.table.idCard') . "：" => text(["name" => "idCard", 'blur' => 'getBirthDay', "value" => $info['idCard']]),
                    L('staffProfiles.table.nation') . "：" => select(array('name' => 'nation', 'title' => L('staffProfiles.table.nation'), 'class' => 'select', 'value' => $info['nation'], 'option' => para('nationOption', '、'))),
                ],
                [
                    L('staffProfiles.table.homeTown') . "：" => repeatSelect(array('name' => 'homeTown', 'title' => L('staffProfiles.table.homeTown'), 'sqlForm' => 'region', 'sqlField' => 'province', 'value' => $info['homeTown'])),
                    must . L('staffProfiles.table.education') . "：" => select(array('name' => 'education', 'title' => L('staffProfiles.table.education'), 'class' => 'select', 'value' => $info['education'], 'option' => para('education', '，'))),
                    L('staffProfiles.table.major') . "：" => text(["name" => "major", "value" => $info['major']]),
                    L('staffProfiles.table.college') . "：" => text(["name" => "college", "value" => $info['college']]),
                ],
                [
                    L('staffProfiles.table.workInDate') . "：" => text(["name" => "workInDate", 'laydate' => ['type'=>'year'], "unit" => '年', "value" => $info['workDate']]),
                    L('staffProfiles.table.jobTitle') . '：' => select(array('name' => 'jobTitle', 'title' => L('staffProfiles.table.choose'), 'class' => 'select', 'value' => $info['jobTitle'], 'option' => explode('，', para('jobTitleOption')))),
                    L('staffProfiles.table.marriage') . "：" => radio(["name" => "marriage", 'value' => $talentObj->marryOption, "checked" => $info['marriage']]),
                    L('staffProfiles.table.politicsStatus') . "：" => select(array('name' => 'politicsStatus', 'title' => L('staffProfiles.table.politicsStatus'), 'class' => 'select', 'value' => $info['politicsStatus'], 'option' => explode('，', para('politicsStatus')))),
                ],
                [
                    L('staffProfiles.table.residenceType') . "：" => radio(["name" => "residenceType", 'value' => $talentObj->residenceTypeOption, "checked" => $info['residenceType']]),
                    L('staffProfiles.table.residenceAddress') . "：" => text(["name" => "residenceAddress", "value" => $info['residenceAddress']]),
                    L('staffProfiles.table.liveAddress') . "：" => text(["name" => "liveAddress", "value" => $info['liveAddress']]),
                    L('staffProfiles.table.postCode') . "：" => text(["name" => "postCode", "value" => $info['postCode']]),
                ],
                [
                    L('staffProfiles.table.height') . "：" => text(["name" => "height", 'unit' => 'cm', "value" => $info['height'] > 0 ? $info['height'] : '']),
                    L('staffProfiles.table.weight') . "：" => text(["name" => "weight", 'unit' => 'kg', "value" => $info['weight'] > 0 ? $info['weight'] : '']),
                    L('staffProfiles.table.health') . "：" => select(array('name' => 'health', 'title' => L('staffProfiles.table.health'), 'class' => 'select', 'value' => $info['health'], 'option' => explode('，', para('healthOption')))),
                ],
                [
                    L('staffProfiles.table.secContactName') . "：" => text(["name" => "secContactName", "value" => $info['secContactName']]),
                    L('staffProfiles.table.secContactRelation') . "：" => text(["name" => "secContactRelation", "value" => $info['secContactRelation']]),
                    L('staffProfiles.table.secContactTel') . "：" => text(["name" => "secContactTel", "value" => $info['secContactTel']]),
                    L('staffProfiles.table.isProhibition') . "：" => radio(["name" => "isProhibition", 'value' => ['无', '有'], "checked" => $info['isProhibition'] ?: '无']),
                ],
                [
                    L('staffProfiles.table.text') . "：" => textarea(["name" => "text", "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'title' => L('staffProfiles.table.learning_experience'),
            'html' => $this->listTable(array('tr' => $educationTr, 'end' => true, 'displayFields' => false)),
        ]);
        $body .= $this->editList([
            'title' => L('staffProfiles.table.work_experience'),
            'html' => $this->listTable(array('tr' => $workTr, 'end' => true, 'displayFields' => false)),
        ]);
        $body .= $this->editList([
            'title' => L('staffProfiles.table.family_member'),
            'html' => $this->listTable(array('tr' => $familyTr, 'end' => true, 'displayFields' => false)),
        ]);
        $body .= $this->editList([
            'id' => 'operateCredentialsID',
            'title' => L('staffProfiles.table.operate_credentials')."<span style='float: none;color: black;margin-left: 10px;' onclick=\"layer('".self::page."','credentialsEdit',{talentId:'" . $staff['stid'] . "',id:''})\" class='spanButton'>新增</span>\n",
            'html' => $this->listTable(array('tr' => $credentialsTr, 'end' => true, 'displayFields' => false)),
        ]);
        $body .= $this->editBlock([
            L('staffProfiles.table.entry_data') => $talentObj->photo($photo),
            L('staffProfiles.table.enclosure') => fileUploadClass::addFileComponent($info['id'], '人才库', self::page, self::page . 'EntryForm')
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(array('name' => 'id', 'value' => $info['id'])) . "<div class='hidden'><input name=\"type\" type=\"hidden\" ><input name='imgFile' accept=\"image/*\" id='imgFile' type='file' onchange=\"uploadImgFile('{$this->get('cla')}EntryForm',root+'control/adIndex.html?cla=talentPool&fun=uploadIco')\"></div>",
        ]);
        $data['html'] .= $talentObj->editJs();
        //返回
        return $this->tab($data);
    }

    public function credentialsEdit()
    {
        $id =$this->post('id')?:self::getId();
        $info = query('operate_credentials', " id = '" . $id . "' ");
        $checked = $info['isLong']?'checked':'';
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    "<div class='small-title'>基本信息</div>".hidden(array('name' => 'talentId', 'value' => $this->post('talentId')))
                ],
                [
                    must . "证照类别：" => select(["name" => "type", 'option' => explode('，', para('certType')), 'title' => '证照类别', 'value' => $info['type']])
                ],
                [
                    must . "证照名称：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                    "证照编号：" => text(["name" => "orderNo", 'class' => 'text', "value" => $info['orderNo']]),
                ],
                [
                    must . "发证日期：" => text(["name" => "startDate", 'laydate' => [], 'class' => 'text', "value" => $info['startDate']]),
                    must . "发证机关：" => text(["name" => "official", 'class' => 'text', "value" => $info['official']]),
                ],
                [
                    must . "有效期至：" => "<div class='flex-box'>".text(["name" => "endDate", 'laydate' => [], 'class' => 'text', "value" => $info['endDate']])."<label class='checkbox width100'><input name='isLong' type='checkbox' $checked value='1'><span></span>&nbsp;永久</label></div>",
                    must . "下次审核日期：" => text(["name" => "auditDate", 'laydate' => [], 'class' => 'text', "value" => $info['auditDate']]),
                ],
                [
                    "提前提醒天数：" => text(["name" => "limitDay", 'class' => 'text', "value" => $info['limitDay']]),
                    "备注：" => textarea(["name" => "text", 'class' => 'textarea', "value" => $info['text']]),
                ],
                [
                    "<div class='small-title'>附件</div>" .
                    fileUploadClass::addFileComponent($info['id'], '证照管理', self::page, 'staffProfilesCredentialsEditForm')
                ],
            ],
        ]);
        $button = "<input onclick=\"credentialsAddRow();\"  type='button' class='button m-l-5' value='" . L('toolCollection.addMx.sub') . "'>";
        //返回
        return $this->layer(["title" => L('job.button.editor').self::title, "height" => 600, "width" => 1100, "remove" => 1, "html" => $html, "button" => $button]);
    }

    public function credentialsEditEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $fileIdArr = $this->post('fileId');
        $field = [
            'type' => $this->post('type'),
            'startDate' => $this->post('startDate'),
            'endDate' => $this->post('isLong')?'':$this->post('endDate'),
            'isLong' => $this->post('isLong'),
            'name' => $this->post('name'),
            'orderNo' => $this->post('orderNo'),
            'official' => $this->post('official'),
            'auditDate' => $this->post('auditDate'),
            'remindStid' => $this->post('remindStid'),
            'limitDay' => $this->post('limitDay'),
            'text' => $this->post('text'),
            'time' => date('Y-m-d H:i:s'),
        ];
        //判断
        if(empty($field['isLong']) && empty($field['endDate'])){
            $json['warn'] = '请选择有效期至';
        } elseif(empty($field['isLong']) && empty($field['auditDate'])){
            $json['warn'] = '请选择下次审核日期';
        } elseif(!$field['isLong'] && strtotime($field['startDate']) >= strtotime($field['endDate'])){
            $json['warn'] = '有效期不能小于等于发证日期';
        }else {
            $liButton = $field['name'];
            $fileId = "";
            if(!empty($fileIdArr)){
                $fileId = implode(",",$fileIdArr);
                foreach ($fileIdArr as $item){
                    $fileData = query('file',"id='{$item}'");
                    $dominate = array(
                        "download" => array("name" => $fileData['name'], "href" => $fileData['src']),
                    );
                    if (in_array($fileData['format'], array("doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"))) {
                        $dominate['preview'] = array("format" => $fileData['format'], "name" => $fileData['name'], "href" => $fileData['src']);
                    } elseif (in_array($fileData['format'], array("png", "gif", "jpg"))) {
                        $dominate['img'] = array("title" => "在线预览", "href" => $fileData['src']);
                    }
                    $liButton .= $fileData['name'].$this->dominate($dominate);
                }
            }
            $tr[] = [
                componentClass::tablePperation('', "credentialsDelRow(this)"),
                hidden(array('name' => 'operateCredentialsId[]', 'value' => $id)) .
                hidden(array('name' => 'operateCredentialstype[]', 'value' => $field['type'])) .
                hidden(array('name' => 'operateCredentialsstartDate[]', 'value' => $field['startDate'])) .
                hidden(array('name' => 'operateCredentialsisLong[]', 'value' => $field['isLong'])) .
                hidden(array('name' => 'operateCredentialsname[]', 'value' => $field['name'])) .
                hidden(array('name' => 'operateCredentialsorderNo[]', 'value' => $field['orderNo'])) .
                hidden(array('name' => 'operateCredentialsofficial[]', 'value' => $field['official'])) .
                hidden(array('name' => 'operateCredentialsauditDate[]', 'value' => $field['auditDate'])) .
                hidden(array('name' => 'operateCredentialsremindStid[]', 'value' => $field['remindStid'])) .
                hidden(array('name' => 'operateCredentialslimitDay[]', 'value' => $field['limitDay'])) .
                hidden(array('name' => 'operateCredentialstext[]', 'value' => $field['text'])) .
                hidden(array('name' => 'operateCredentialsendDate[]', 'value' => $field['endDate'])) .
                hidden(array('name' => 'operateCredentialstime[]', 'value' => $field['time'])) .
                hidden(array('name' => 'operateCredentialsfileId[]', 'value' => $fileId)) .
                $liButton,
                $field['isLong'] == 1 ? '永久' : $field['endDate'],
                $field['time'],
            ];
            //返回
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
            $json['warn'] = 2;

        }
        return json_encode($json, 320);
    }


    /**
     *入职信息保存
     */
    public function entryEdit()
    {
        $id = $this->post('id');
        $staff = query('staff', " talentId = '$id'");
        $field = [
            'email' => $this->post('email'),
            'name' => $this->post('name'),
            'sex' => $this->post('sex'),
            'tel' => $this->post('tel'),
            'idCard' => $this->post('idCard'),
            'birthDay' => $this->post('idCard')?self::getBirthdayFromIDCard($this->post('idCard')):'',
            'nation' => $this->post('nation'),
            'homeTown' => $this->post('homeTown'),
            'height' => $this->post('height'),
            'weight' => $this->post('weight'),
            'health' => $this->post('health'),
            'education' => $this->post('education'),
            'major' => $this->post('major'),
            'college' => $this->post('college'),
            'workDate' => $this->post('workInDate'),
            'marriage' => $this->post('marriage'),
            'politicsStatus' => $this->post('politicsStatus'),
            'residenceAddress' => $this->post('residenceAddress'),
            'residenceType' => $this->post('residenceType'),
            'liveAddress' => $this->post('liveAddress'),
            'secContactName' => $this->post('secContactName'),
            'secContactTel' => $this->post('secContactTel'),
            'secContactRelation' => $this->post('secContactRelation'),
            'jobTitle' => $this->post('jobTitle'),
            'text' => $this->post('text'),
            'isProhibition' => $this->post('isProhibition'),
            'postCode' => $this->post('postCode'),
        ];
        $annotation = [
            'name' => L('staffProfiles.table.name'),
            'sex' => L('staffProfiles.table.sex'),
            'tel' => L('staffProfiles.table.tel'),
            'idCard' => L('staffProfiles.table.idCard'),
            'education' => L('staffProfiles.table.education'),
            'workDate' => L('staffProfiles.table.workInDate'),
            'height' => L('staffProfiles.table.height'),
            'weight' => L('staffProfiles.table.weight'),
            'secContactTel' => L('staffProfiles.table.secContactTel'),
        ];
        $rules = [
            'name' => 'required',
            'sex' => 'required',
            'tel' => 'required|tel',
            'idCard' => 'required|id_card',
            'education' => 'required',
            'workDate' => 'numeric|min:1|max:'.date("Y"),
            'height' => 'numeric',
            'weight' => 'numeric',
            'secContactTel' => 'tel',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        //学习经历
        $studyIdArr = $this->post('studyId') ?? [];
        $educationDateArr = $this->post('educationDate');
        $schoolArr = $this->post('school');
        $schoolMajorArr = $this->post('schoolMajor');
        $certificateArr = $this->post('certificate');
        //工作经历
        $workIdArr = $this->post('workId') ?? [];
        $workDateArr = $this->post('workDate');
        $companyNameArr = $this->post('companyName');
        $positionArr = $this->post('position');
        $contentArr = $this->post('content');
        $causeArr = $this->post('cause');
        //家庭成员
        $familyIdArr = $this->post('familyId') ?? [];
        $memberNameArr = $this->post('memberName');
        $relationArr = $this->post('relation');
        $memberCompanyArr = $this->post('memberCompany');
        $contactTelArr = $this->post('contactTel');
        //操作证书
        $operateCredentialsIdArr = $this->post('operateCredentialsId') ?? [];
        $operateCredentialsTypeArr = $this->post('operateCredentialstype');
        $operateCredentialsStartDateArr = $this->post('operateCredentialsstartDate');
        $operateCredentialsIsLongArr = $this->post('operateCredentialsisLong');
        $operateCredentialsNameArr = $this->post('operateCredentialsname');
        $operateCredentialsOrderNoArr = $this->post('operateCredentialsorderNo');
        $operateCredentialsOfficialArr = $this->post('operateCredentialsofficial');
        $operateCredentialsAuditDateArr = $this->post('operateCredentialsauditDate');
        $operateCredentialsRemindStidArr = $this->post('operateCredentialsremindStid');
        $operateCredentialsLimitDayArr = $this->post('operateCredentialslimitDay');
        $operateCredentialsTextArr = $this->post('operateCredentialstext');
        $operateCredentialsEndDateArr = $this->post('operateCredentialsendDate');
        $operateCredentialsTimeArr = $this->post('operateCredentialstime');
        $operateCredentialsFileIdArr = $this->post('operateCredentialsfileId');
        //附件
        $fileIdArr = $this->post('fileId');

        $where = " id = '$id' ";
        $info = query('talent_pool', $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('staffProfiles.tip.permission_edit_warn');
            //} elseif (!preg_match("/^([\x{4e00}-\x{9fa5}]+)$/u", $field['name']) && !preg_match("/^[a-z]+$/i", $field['name'])) {
        } elseif (!preg_match("/^[\x{4e00}-\x{9fa5}a-zA-Z0-9]+$/u", $field['name'])) {
            $json['warn'] = L('staffProfiles.tip.name_warn');
        } elseif (!empty($field['email']) && preg_match(checkEmail, $field['email']) == 0) {
            $json['warn'] = L('staffProfiles.tip.email_warn');
        } elseif (!empty($field['idCard']) && (static::total(array('sql' => "SELECT count(*) AS total FROM talent_pool where idCard = '{$field['idCard']}' and id !='$id'")))) {
            $json['warn'] = L('staffProfiles.tip.idCard_repeat_warn');
        } elseif (!$info['id']) {
            $json['warn'] = L('staffProfiles.tip.find_none_staff');
        } elseif (!empty($field['birthDay']) && $this->age($field['birthDay']) < 16) {
            $json['warn'] = L('staffProfiles.tip.age_warn');
        } elseif (!empty($this->post('manager')) && $this->post('manager') == $staff['stid']) {
            $json['warn'] = L('staffProfiles.tip.manager_warn');
        } elseif (!empty($this->post('orderNo')) && static::total(array('table' => self::table, 'where' => "orderNo = '" . $this->post('orderNo') . "' and stid !='$staff[stid]'")) > 0) {
            $json['warn'] = '已存在此编号的员工';
        } else {
            $this->startTrans();//开启事务
            $isPass = true;//事务通过标志
            $json['warn'] = static::update([
                "table" => 'talent_pool',
                "field" => $field,
                "where" => $where,
            ]);
            /******工作信息*******/
            $entryRecord = query('staff_entry_record', " talentId = '$info[id]'  order by time desc");
            if (empty($entryRecord['id'])) {
                //针对管理员  如果没有入职记录 则生成一条
                $userNo = codeTemplateClass::generateCode('staffEntryRecord', [
                    'prefix' => 'RZSQ' . date('Ymd'),
                    'table' => 'staff_entry_record',
                    'field' => 'orderNo',
                    'where' => '',
                ], []);
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $entryField = [
                    'jobId' => $staff['jobId'],
                    'contractType' => '劳动合同',
                    'contractLimitType' => '无固定期限',
                    'entryDate' => $this->date,
                    'endDate' => $this->date,
                    'id' => self::getId(),
                    'state' => '已通过',
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'deptName' => $department['name'],
                    'talentId' => $info['id'],
                ];
                $warn = static::insert(array('table' => 'staff_entry_record', 'field' => $entryField));
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = L('staffProfiles.tip.entry_record_failed');
                }
            }


            //添加或更新学习经历
            if (is_array($studyIdArr)) {
                foreach ($studyIdArr as $k => $nid) {
                    $studyField = [
                        'studyDate' => $educationDateArr[$k],
                        'college' => $schoolArr[$k],
                        'major' => $schoolMajorArr[$k],
                        'certificate' => $certificateArr[$k],
                    ];
                    $exist = static::total(array('table' => 'study_history', 'where' => " and id = '$nid'"));
                    if(empty(array_filter($studyField, 'strlen'))) {
                        if ($exist > 0) delete(array('table' => 'study_history', 'where' => " id = '$nid' "));
                        continue;
                    }
                    if ($exist > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'study_history',
                            "field" => $studyField,
                            "where" => " id = '$nid'",
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'study_history',
                            "field" => array_merge($studyField, [
                                'id'       => $nid,
                                'talentId' => $id,
                                'time'     => $this->time,
                            ]),
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加或更新工作经历
            if (is_array($workIdArr)) {
                foreach ($workIdArr as $k => $nid) {
                    $workField = [
                        'companyName' => $companyNameArr[$k],
                        'position' => $positionArr[$k],
                        'content' => $contentArr[$k],
                        'cause' => $causeArr[$k],
                        'workDate' => $workDateArr[$k],
                    ];
                    $exist = static::total(array('table' => 'job_history', 'where' => " and id = '$nid'"));
                    if(empty(array_filter($workField, 'strlen'))) {
                        if ($exist > 0) delete(array('table' => 'job_history', 'where' => " id = '$nid' "));
                        continue;
                    }
                    if ($exist > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'job_history',
                            "field" => $workField,
                            "where" => " id = '$nid'",
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'job_history',
                            "field" => array_merge($workField, [
                                'id'       => $nid,
                                'talentId' => $id,
                                'time'     => $this->time,
                            ]),
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加或更新家庭成员
            if (is_array($familyIdArr)) {
                foreach ($familyIdArr as $k => $nid) {
                    $familyField = [
                        'name' => $memberNameArr[$k],
                        'relation' => $relationArr[$k],
                        'company' => $memberCompanyArr[$k],
                        'contactTel' => $contactTelArr[$k],
                    ];
                    $exist = static::total(array('table' => 'talent_family', 'where' => " and id = '$nid'"));
                    if(empty(array_filter($familyField, 'strlen'))) {
                        if ($exist > 0) delete(array('table' => 'talent_family', 'where' => " id = '$nid' "));
                        continue;
                    }
                    if ($exist > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'talent_family',
                            "field" => $familyField,
                            "where" => " id = '$nid'",
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'talent_family',
                            "field" => array_merge($familyField, [
                                'id'       => $nid,
                                'talentId' => $id,
                                'time'     => $this->time,
                            ]),
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            delete(array('table' => 'operate_credentials', 'where' => " talentId = '$info[id]' "));
            //操作证书
            if(is_array($operateCredentialsIdArr)){
                foreach ($operateCredentialsIdArr as $k => $nid) {
                    $operateCredentialsField = [
                        'type' => $operateCredentialsTypeArr[$k],
                        'startDate' => $operateCredentialsStartDateArr[$k],
                        'endDate' => $operateCredentialsIsLongArr[$k] ? '' : $operateCredentialsEndDateArr[$k],
                        'isLong' => $operateCredentialsIsLongArr[$k],
                        'name' => $operateCredentialsNameArr[$k],
                        'orderNo' => $operateCredentialsOrderNoArr[$k],
                        'official' => $operateCredentialsOfficialArr[$k],
                        'auditDate' => $operateCredentialsAuditDateArr[$k],
                        'remindStid' => $staff['stid'],
                        'limitDay' => $operateCredentialsLimitDayArr[$k],
                        'text' => $operateCredentialsTextArr[$k],
                        'time' => $operateCredentialsTimeArr[$k],
                    ];
                    $exist = static::total(array('table' => 'operate_credentials', 'where' => " and id = '$nid'"));
                    if(empty(array_filter($operateCredentialsField, 'strlen'))) {
                        if ($exist > 0) delete(array('table' => 'operate_credentials', 'where' => " id = '$nid' "));
                        continue;
                    }
                    if ($exist > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'operate_credentials',
                            "field" => $operateCredentialsField,
                            "where" => " id = '$nid'",
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'operate_credentials',
                            "field" => array_merge($operateCredentialsField, [
                                'id'       => $nid,
                                'talentId' => $id,
                            ]),
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }else{
                        update(array('table' => 'file', 'field' => ['targetId' => ''], 'where' => " targetId = '{$nid}'"));
                        if(!empty($operateCredentialsFileIdArr[$k])){
                            $operateCredentialsFileId = explode(',',$operateCredentialsFileIdArr[$k]);
                            update(array('table' => 'file', 'field' => ['targetId' => $nid], 'where' => " targetId = '' and id in ('" . implode("','", $operateCredentialsFileId) . "')"));
                        }
                    }
                }
            }

            //添加主表ID到附件表
            if (is_array($fileIdArr)) {
                $warn = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                if ($warn != '更新成功') {
                    $json['warn'] = $warn;
                    $isPass = false;
                }
            }
            $userNo = codeTemplateClass::generateCode('staffProfiles', [
                'prefix' => 'YM' . date('Ymd'),
                'table' => 'staff',
                'field' => 'orderNo',
                'where' => '',
            ], []);
            $warn = update(array('table' => 'staff', 'field' => ['name' => $field['name'], 'orderNo' => $this->post('orderNo') ?: $userNo, 'manager' => $this->post('manager'), 'subjectId' => $this->post('subjectId'), 'tel' => $field['tel']], 'where' => " stid = '$staff[stid]'"));
            if ($warn != '更新成功') {
                $json['warn'] = $warn;
                $isPass = false;
            }
            //更新账号表的姓名和电话
            $warn = update(array('table' => 'user', 'field' => ['name' => $field['name'], 'tel' => $field['tel']], 'where' => " stid = '$staff[stid]'"));
            if ($warn != '更新成功') {
                $json['warn'] = L('staffProfiles.tip.user_warn');
            }

            if ($isPass && in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();//提交事务
                //删除不在此ID中的数据
                delete(array('table' => 'talent_family', 'where' => " id not in ('" . implode("','", $familyIdArr) . "') and talentId = '$staff[talentId]'"));
                delete(array('table' => 'job_history', 'where' => " id not in ('" . implode("','", $workIdArr) . "') and talentId = '$staff[talentId]'"));
                delete(array('table' => 'study_history', 'where' => " id not in ('" . implode("','", $studyIdArr) . "') and talentId = '$staff[talentId]'"));
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $field['name'], $staff['stid']], L('staffProfiles.other.staff_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $staff['stid'];
            } else {
                $this->rollback();//回滚
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " stid = '{$this->get('id')}'");
        if (empty($info['stid'])) {
            $html = L('staffProfiles.detail.find_none_staff');
        } else {
            $talentObj = new talentPoolClass();
            //人才库信息
            $talent = query('talent_pool', " id = '$info[talentId]'");
            //工作信息
            $entry = query('staff_entry_record', " talentId = '$info[talentId]' order by time desc");
            //转正记录
            $staffFormal = query('staff_formal', " talentId = '$info[talentId]' order by time desc");
            //离职记录
            $staffQuit = query('staff_quit_record', " staffId = '$info[stid]' order by time desc");
            //菜单
            $data = array(
                "id" => $info['stid'],
                "name" => $info['name'],
                'menu' => [
                    "detail" => L('staffProfiles.detail.base'),
                    //"studyHistory" => array("name" => L('staffProfiles.detail.social_resume'), "cla" => "talentPool", "fun" => "studyHistory"),
                    'evaluation' => L('staffProfiles.detail.evaluation'),
                    "record" => L('staffProfiles.detail.change_record'),
                    "trainRecord" => array("name" => L('staffProfiles.detail.train_record'), "cla" => "trainingRecord", "fun" => "trainRecord"),
                    "achievements" => array("name" => L('staffProfiles.detail.performance_record'), "cla" => "performanceScore", "fun" => "achievements"),
                    "clockRecord" => array("name" => L('staffProfiles.detail.attendance_record'), "cla" => "workSign", "fun" => "clockRecord"),
                    "salaryRecord" => array("name" => L('staffProfiles.detail.salary_record'), "cla" => "paySlip", "fun" => "salaryRecord"),
                    "rewardsRecord" => array("name" => L('staffProfiles.detail.reward_record'), "cla" => "rewards", "fun" => "rewardsRecord"),
                    "asset" => L('staffProfiles.detail.asset_pick'),
                    "setting" => L('staffProfiles.detail.staff_setting'),
                ],
            );
            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => L('staffProfiles.detail.edit'),
                    "type" => "顶部页卡",
                    "title" => L('staffProfiles.detail.edit'),
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=entry&id=' . $info['stid'],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, 'del')) {
                //按钮
                $button[] = [
                    "name" => L('staffProfiles.button.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['stid']],
                ];
            }

            if ($info['state'] == '留职') {
                //按钮
                $button[] = [
                    "name" => L('staffProfiles.detail.duty'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'recover', "id" => $info['stid']],
                ];
            }

            $ico = [];
            $all = find(array('table' => 'file', 'where' => "targetId = '$talent[id]' and target in ('入职登记表','身份证正面','身份证背面','毕业证','学位证','银行卡','离职证明','体检报告','职称证书','竞业限制协议')"));
            foreach ($all['array'] as $array) {
                $ico[$array['target']] = $array['src'];
            }
            $photo = array(
                array("title" => L('staffProfiles.table.front_of_id_card'), 'type' => '身份证正面', "url" => $ico['身份证正面'] ?? ''),
                array("title" => L('staffProfiles.table.back_of_id_card'), 'type' => '身份证背面', "url" => $ico['身份证背面'] ?? ''),
                array("title" => L('staffProfiles.table.diploma'), 'type' => '毕业证', "url" => $ico['毕业证'] ?? ''),
                array("title" => L('staffProfiles.table.degree_diploma'), 'type' => '学位证', "url" => $ico['学位证'] ?? ''),
                array("title" => L('staffProfiles.table.bank_card'), 'type' => '银行卡', "url" => $ico['银行卡'] ?? ''),
                array("title" => L('staffProfiles.table.registration_form'), 'type' => '入职登记表', "url" => $ico['入职登记表'] ?? ''),
                array("title" => L('staffProfiles.table.leaving_certificate'), 'type' => '离职证明', "url" => $ico['离职证明'] ?? ''),
                array("title" => L('staffProfiles.table.medical_report'), 'type' => '体检报告', "url" => $ico['体检报告'] ?? ''),
                array("title" => L('staffProfiles.table.Professional_certificate'), 'type' => '职称证书', "url" => $ico['职称证书'] ?? ''),
                array("title" => L('staffProfiles.table.competition_agreement'), 'type' => '竞业限制协议', "url" => $ico['竞业限制协议'] ?? ''),
            );
            /*******附件****************/
            $fileCollection = fileUploadClass::showFile($talent['id'], '人才库');
            //职位
            $job = query('job', " id = '$info[jobId]'");
            //合同信息
            $staffContract = query('staff_contract', " staffId = '$info[stid]' order by signDate desc,time desc");
            //社会保险
            $staffInsure = query('staff_insure', "staffId = '$info[stid]' order by insureDate desc,time desc");
            //社会履历
            $tr[] = [L('staffProfiles.table.study_date'),
                L('staffProfiles.table.university'),
                L('staffProfiles.table.study_major'),
                L('staffProfiles.table.achievements')];
            $sql = find(array("table" => "study_history", "where" => " talentId = '" . $talent['id'] . "' order by list asc "));
            foreach ($sql['array'] as $array) {
                $tr[] = array($array['studyDate'], $array['college'], $array['major'], $array['certificate']);
            }

            $wrokTr[] = [L('staffProfiles.table.work_date_start'),
                L('staffProfiles.table.employed'),
                L('staffProfiles.table.station'),
                L('staffProfiles.table.work_content'),
                L('staffProfiles.table.quit_reason')];
            $sql = find(array("table" => "job_history", "where" => " talentId = '" . $talent['id'] . "' order by list asc "));
            foreach ($sql['array'] as $array) {
                $wrokTr[] = array($array['workDate'], $array['companyName'], $array['position'], $array['content'], $array['cause']);
            }

            $faTr[] = [L('staffProfiles.table.name'),
                L('staffProfiles.table.relationship'),
                L('staffProfiles.table.work_unit'),
                L('staffProfiles.table.contactTel')];
            $sql = find(array("table" => "talent_family", "where" => " talentId = '" . $talent['id'] . "' order by list asc "));
            foreach ($sql['array'] as $array) {
                $faTr[] = array($array['name'], $array['relation'], $array['company'], $array['contactTel']);
            }

            /*****操作证书*********/
            $credentialsTr[] = [
                L('staffProfiles.table.operate_credentials'),
                L('staffProfiles.table.credentialsDueDate'),
                L('staffProfiles.table.credentialsUploadDate'),
            ];
            $result = find(array(
                'field' => "id as credentialsId,type,startDate,isLong,name,endDate,orderNo,official,auditDate,remindStid,limitDay,text,time",
                'table' => "operate_credentials where talentId = '{$talent['id']}'"
            ));
            if(count($result['array']) > 0) {
                foreach ($result['array'] as $k=>$array) {
                    $array['list'] = $k+1;
                    $liButton = $array['name'];
                    $fileIdArr = find(['table'=>'file','where'=>"targetId='{$array['credentialsId']}'"]);
                    if(!empty($fileIdArr['array'])){
                        foreach ($fileIdArr['array'] as $item){
                            $dominate = array(
                                "download" => array("name" => $item['name'], "href" => $item['src']),
                            );
                            if (in_array($item['format'], array("doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"))) {
                                $dominate['preview'] = array("format" => $item['format'], "name" => $item['name'], "href" => $item['src']);
                            } elseif (in_array($item['format'], array("png", "gif", "jpg"))) {
                                $dominate['img'] = array("title" => "在线预览", "href" => $item['src']);
                            }
                            $liButton .= $item['name'].$this->dominate($dominate);
                        }
                    }
                    $credentialsTr[] = [
                        $liButton,
                        $array['isLong'] == 1 ? '永久' : $array['endDate'],
                        $array['time'],
                    ];
                }
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                L('staffProfiles.detail.info') => array(
                    array(
                        L('staffProfiles.table.name') => $info['name'],
                        L('staffProfiles.table.sex') => $talent['sex'],
                        L('staffProfiles.table.tel') => $info['tel'],
                        L('staffProfiles.table.email') => $talent['email'],
                    ),
                    array(
                        L('staffProfiles.table.idCard') => $talent['idCard'],
                        L('staffProfiles.table.birthDay') => $talent['birthDay'] .'（'.$this->age($talent['birthDay']) . '岁）',
                        L('staffProfiles.table.nation') => $talent['nation'],
                        L('staffProfiles.table.homeTown') => $talent['homeTown'],
                    ),
                    array(
                        L('staffProfiles.table.education') => $talent['education'],
                        L('staffProfiles.table.major') => $talent['major'],
                        L('staffProfiles.table.college') => $talent['college'],
                        L('staffProfiles.table.workInDate') => $talent['workDate'] . '年' .'（已工作'. (date("Y")-(int)$talent['workDate']) . '年）',
                    ),
                    array(
                        L('staffProfiles.table.jobTitle') => $talent['jobTitle'],
                        L('staffProfiles.table.marriage') => $talent['marriage'],
                        L('staffProfiles.table.politicsStatus') => $talent['politicsStatus'],
                        L('staffProfiles.table.residenceType') => $talent['residenceType'],
                    ),
                    array(
                        L('staffProfiles.table.residenceAddress') => $talent['residenceAddress'],
                        L('staffProfiles.table.liveAddress') => $talent['liveAddress'],
                        L('staffProfiles.table.postCode') => $talent['postCode'],
                    ),
                    array(
                        L('staffProfiles.table.height') => $talent['height'] . 'cm',
                        L('staffProfiles.table.weight') => $talent['weight'] . 'kg',
                        L('staffProfiles.table.health') => $talent['health'],
                    ),
                    array(
                        L('staffProfiles.table.secContactName') => $talent['secContactName'],
                        L('staffProfiles.table.secContactRelation') => $talent['secContactRelation'],
                        L('staffProfiles.table.secContactTel') => $talent['secContactTel'],
                    ),
                    array(
                        L('staffProfiles.table.text') => pre($talent['text']),
                    ),
                ),
                L('staffProfiles.detail.work_info') => array(
                    array(
                        L('staffProfiles.table.department') => departmentClass::getTypeName($job['departmentId']),
                        L('staffProfiles.table.job') => $job['name'],
                        L('job.table.jobType') => $job['type'],
                        L('staffProfiles.table.superior') => self::findStaff($info['manager']),
                    ),
                    array(
                        L('staffProfiles.table.entryDate') => $entry['entryDate'],
                        L('staffProfiles.table.tryDate') => $entry['endDate'],
                        L('staffProfiles.table.formalDate') => $staffFormal['confirmDate'],
                        L('staffProfiles.table.contractType') => $staffContract['contractType'],
                    ),
                    array(
                        L('staffProfiles.table.contractyear') => $staffContract['contractLimitType'] == '无固定期限' ? $staffContract['contractLimitType'] : $staffContract['contractLimitType'] . '-' . $staffContract['contractYear'] . '个月',
                        L('staffProfiles.table.workSalary') => $staffContract['workSalary'],
                        L('staffProfiles.table.contractDate') => self::null($staffContract['signDate']),
                        L('staffProfiles.table.contractStartAndEnd') => self::null($staffContract['signStartDate']) . '至' . self::null($staffContract['signEndDate']),
                    ),
                    array(
                        L('staffProfiles.table.contractDismiss') => self::null($staffContract['stopDate']),
                        L('staffProfiles.table.insure') => $staffContract['insure'],
                        L('staffProfiles.table.insureDate') => self::null($staffInsure['insureDate']),
                        L('staffProfiles.detail.insureNo') => $staffInsure['insureNo'],
                    ),
                    array(
                        L('staffProfiles.detail.insure_state') => $staffInsure['workFlow'],
                        L('staffProfiles.table.work_text') => $entry['text'],
                    ),
                ),
                L('staffProfiles.detail.work_contract') => array(
                    array(
                        fileUploadClass::showFile($staffContract['id']),
                    ),
                ),
                L('staffProfiles.detail.system_info') => array(
                    array(
                        L('staffProfiles.table.orderNo') => $info['orderNo'],
                        L('staffProfiles.table.state') => $info['state'],
                        L('staffProfiles.table.quitDay') => self::null($staffQuit['confirmDate']),
                        L('staffProfiles.detail.creator') => self::findStaff($info['stid']),
                    ),
                    array(
                        L('staffProfiles.detail.creatTime') => $info['time'],
                        L('staffProfiles.detail.updateTime') => $info['updateTime'],
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '学习经历',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '工作经历',
                'html' => $this->listTable(array('tr' => $wrokTr, 'showEmpty' => true, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '家庭成员',
                'html' => $this->listTable(array('tr' => $faTr, 'showEmpty' => true, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '操作证书',
                'html' => $this->listTable(array('tr' => $credentialsTr, 'showEmpty' => true, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailBlock([
                L('staffProfiles.table.entry_data') => $talentObj->photo($photo),
                L('staffProfiles.table.enclosure') => $fileCollection
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * @param $data
     * @return string
     */
    public function photo($data): string
    {
        $li = "";
        foreach ($data as $num => $array) {
            //编辑表单
            $click = '';
            if (!empty($array['id'])) {
                $click = "<img  src='" . root . "img/images/clickEdit.png' onClick=\"clickUpload('{$array['type']}','{$array['id']}')\" class='clickIco edit-ico'>";
                if (!empty($array['fileId'])) {
                    $click = "<img  src='" . root . "img/control/singleDel.svg' onClick=\"delSingleIco('{$array['fileId']}')\" class='clickIco edit-ico'>";
                }
            }
            //点击显示大图功能
            if (empty($array['url'])) {
                $img = "<img class='smallImg imgHover' data-type='{$array['type']}' src='" . root . "img/images/emptyImg.jpg'>";
            } else {
                if (strstr($array['url'], "http") !== false) {
                    $r = "";
                } else {
                    $r = root;
                }
                $img = "<a target='_blank' href='" . $r . $array['url'] . "' title='点击查看大图'><img data-type='{$array['type']}' class='smallImg imgHover' src='" . $r . $array['url'] . "'></a>";
            }
            //打印本图像框
            $li .= "
			<li>
				" . $click . "
				<p>" . $array['title'] . "</p>
				<div>" . $img . "</div>
			</li>
			";
        }
        $html = <<<efo
		<div class='imgSingle'>
			<ul>{$li}</ul>
			<div class='clear'></div>
		</div>
		<div class='hidden'>
            <form name="imgForm">
                <input type="hidden" name="mainId">
                <input type="hidden" name="type">
                <input name='ico' id='ico' type='file' onchange="uploadImgFile('imgForm',root+'control/adIndex.html?cla={$this->get('cla')}&fun=uploadIco','add-file-button')">
            </form>
		</div>
		<script>
		//点击上传图片
        function clickUpload(type,id){
            $('[name=mainId]').val(id)
            $('[name=type]').val(type)
            $('#ico').click();
        }
        //上传图片
        function uploadImgFile(formName,url){
            let form = $("form[name='"+formName+"']")[0];
            let type= $('[name=type]').val();
            let formData = new FormData(form);
            $.ajax({
                type: "POST",
                contentType: false,
                processData: false,
                url: url,
                data: formData,
                cache: false,
                success: function (res) {
                    let result = JSON.parse(res);
                    $("[name='ico']").val('');
                    if (result.warn === 2) {
                        $("[data-type='"+type+"']").attr('src',result.data.src);
                        $("[data-type='"+type+"']").parent().parent().find(".edit-ico").attr('src',root+'img/control/singleDel.svg');
                        $("[data-type='"+type+"']").parent().parent().find(".edit-ico").attr('onclick',"delSingleIco('"+result.data.id+"')")
                    }else{
                        warn(result.warn)
                    }
                },
                error: function (e) {
                    warn("上传失败");
                }
            });
        }
        </script>
efo;
        return $html;
    }

    /**
     *上传图像资料
     */
    function uploadIco()
    {
        $type = $this->post('type');
        $result = $this->saveFile($_FILES['ico'], 'staff', explode(',', para('fileFormat')));
        $info = query(self::table, " stid = '{$this->post('mainId')}'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('staffProfiles.tip.permission_edit_warn');
        } elseif (empty($info['stid'])) {
            $json['warn'] = L('staffProfiles.detail.find_none_staff');
        } elseif (empty($type)) {
            $json['warn'] = L('staffProfiles.tip.find_none_type');
        } elseif (!$result['code']) {
            $json['warn'] = $result['warn'];
        } else {
            $field = match ($type) {
                '头像' => 'ico',
                '工资卡' => 'bankIco'
            };
            $json['warn'] = static::update(array("table" => self::table, "field" => array($field => $result['src']), "where" => " stid = '" . $this->post('mainId') . "' "));
            //添加日志
            if ($json['warn'] == "更新成功") {
                if ($info[$field] != 'img/websiteImg/replaceHead.jpg') {
                    fileDelete($info[$field]);//删除之前的图片
                }

                $json['warn'] = 2;
                $json['data']['src'] = root . $result['src'];
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 资产领用
     *
     * @return bool|string
     */
    public function asset()
    {
        $endDate = $this->date;
        $staff = query('staff', "stid = '" . $this->get('id') . "'");
        $sql = find(array('table' => " `asset_use_detail` as a join `asset_use` as b on a.orderId = b.id", 'field' => " b.receivingDate,a.*", 'where' => " b.state = '已通过' and b.receiver = '$staff[stid]' and a.state != '已归还' order by time desc"));
        $tr[] = array(
            L('staffProfiles.detail.pickDate'),
            L('staffProfiles.detail.asset_orderNo'),
            L('staffProfiles.detail.assetName'),
            L('staffProfiles.detail.brand'),
            L('staffProfiles.detail.model'),
            L('staffProfiles.detail.remind_value') . "（" . static::$unit . "）",
        );
        foreach ($sql['array'] as $array) {
            $asset = query('asset', " id = '$array[atid]'");
            $ratio = assetManagementClass::monthRatio($asset['depreciationMethod'], $asset['discountYear'], $asset['money'], $asset['purchaseMoney'], $asset['depreciationMoney'], $asset['purchaseDate'], $endDate, 1);
            $monthDecMoney = assetManagementClass::monthDecMoney($asset['depreciationMethod'], $asset['purchaseMoney'], $ratio / 100, $asset['purchaseDate'], $endDate, $asset['discountYear'], $asset['money'], $asset['depreciationMoney']);
            $salvage = assetManagementClass::calcRemindMoney($asset['depreciationMethod'], $monthDecMoney, $asset['purchaseDate'], $asset['discountYear'], $asset['purchaseMoney'], $asset['money'], $asset['depreciationMoney'], $endDate);
            $tr[] = array($array['receivingDate'], $asset['orderNo'], $asset['name'], $asset['brand'], $asset['model'], $salvage);
        }
        //构建表单
        $json['html'] = "<div class='p-10'><form name='assetForm'>" . $this->tableMany(array("tr" => $tr,"displayFields" => false)) . "</form></div>";
        //返回
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function recordOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('staffProfiles.detail.orderNo') => text(array("name" => "orderNo")),
                    L('staffProfiles.detail.orderType')   => select(array("name" => "type", 'option' => ['入职', '转正', '调岗', '停薪留职', '离职'])),
                    L('staffProfiles.detail.date') => text(array("name" => "recordDate", 'laydate' => ['type' => 'date', 'range' => '~'])).
                        hidden(array('name' => 'id', 'value' => $this->get('id'))),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 变动记录
     */
    public function record()
    {
        $html = $this->recordOptions(false);
        $button = "";
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    /**
     * 变动记录
     *
     * @return bool|string
     */
    public function recordSearch()
    {
        $id = $this->post('id');
        $where = " and stid = '$id'";
        $and = '';
        $like = [
            'orderNo' => $this->post('orderNo'),
        ];
        $equal = [
            'type' => $this->post('type'),
        ];
        if ($this->post('recordDate')) {
            $timeArr = explode(' ~ ', $this->post('recordDate'));
            $and .= " and recordDate >='{$timeArr[0]}' and  recordDate <='{$timeArr[1]}'";
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'recordDate desc,`time`',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $page = $this->page([
            "table" => "staff_state_record",
            "where" => " {$where} ",
            "order" => $orderBy['orderBy'],
        ]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            $cla = match ($array['type']) {
                '入职' => 'staffEntryRecord',
                '离职' => 'staffQuitRecord',
                '停薪留职' => 'staffStayRecord',
                '调岗' => 'jobApply',
                '转正' => 'staffFormal',
                default => '',
            };
            if ($cla) {
                //跳转路径
                $url = root . 'control/adIndex.html?cla=' . $cla . '&&fun=detail&id=' . $array['sourceId'];
                $dominate = array(
                    "detail" => array("title" => "详情", "click" => "newIframe('" . $array['type'] . "详情','" . $url . "')"),
                );
            } else {
                $dominate = [];
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        $json['html'] = $page['hint'] . $button . "<form name='topicForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 员工设置
     *
     * @return bool|string
     */
    public function setting()
    {
        $staff = query('staff', "stid = '" . $this->get('id') . "'");
        if (!$this->power(self::page, "see")) {
            $json['html'] = L('staffProfiles.tip.permission_see_warn');
        } else {
            $user = query('user', " stid = '$staff[stid]'");
            if ($this->power(self::page, "edit")) {
                $photo = array(
                    array("title" => L('staffProfiles.detail.portrait'), 'type' => '头像', "url" => $staff['ico'], "id" => $staff['stid']),
                    //array("title" => L('staffProfiles.detail.pay_card'), 'type' => '工资卡', "url" => $staff['bankIco'], "id" => $staff['stid']),
                );
                //薪酬编辑按钮
                $salaryButton = "<span style='margin-left: 20px;cursor: pointer' onclick=\"layer('{$this->get('cla')}','salary',{id:'" . $staff['stid'] . "'})\"><img style='width:16px;height:16px' src='" . root . "img/control/edit.svg'></span>";
                $accountButton = "<span style='margin-left: 20px;cursor: pointer' onclick=\"layer('{$this->get('cla')}','accountSet',{id:'" . $staff['stid'] . "'})\"><img style='width:16px;height:16px' src='" . root . "img/control/edit.svg'></span>";
                $userButton = "<span style='margin-left: 20px;cursor: pointer' onclick=\"layer('{$this->get('cla')}','userSet',{id:'" . $staff['stid'] . "'})\"><img style='width:16px;height:16px' src='" . root . "img/control/edit.svg'></span>";
            } else {
                $photo = array(
                    array("title" => L('staffProfiles.detail.portrait'), 'type' => '头像', "url" => $staff['IDCardFront']),
                    //array("title" => L('staffProfiles.detail.pay_card'), 'type' => '工资卡', "url" => $staff['IDCardBack']),
                );
                $salaryButton = '';
                $accountButton = '';
                $userButton = '';
            }

            $field = array(
                L('staffProfiles.detail.salary_setting') . $salaryButton => array(
                    array(
                        L('staffProfiles.detail.bankName') => $staff['bankName'],
                        L('staffProfiles.detail.bankNo') => $staff['bankNum'],
                        L('staffProfiles.detail.personal_part') . "(" . static::$unit . ")" => $staff['personalFund'],
                        L('staffProfiles.detail.company_part') . "(" . static::$unit . ")" => $staff['companyFund'],
                    ),
                ),
                L('staffProfiles.detail.account_stting') . $accountButton => array(

                    array(
                        L('staffProfiles.detail.ding') => $staff['dingtalkId'],
                        L('staffProfiles.detail.wechat_id') => $user['weChatUserId'],
                    ),
                ),

            );
            if (!empty($user['uid'])) {
                $field = array_merge($field,
                    [
                        L('staffProfiles.detail.user_stting') . $userButton => array(

                            array(
                                L('staffProfiles.detail.username') => $user['userName'],
                                L('staffProfiles.detail.role') => $this->findRoleName($user['role']),
                                L('staffProfiles.table.text') => $user['text'],
                            ),
                        ),
                    ]);
            } else {
                $field = array_merge($field,
                    [
                        L('staffProfiles.detail.user_stting') => array(

//                            array(
//                                "<span class='del-row-button' onclick=\"newIframe('新建用户', '" . $this->root . "control/adIndex.html?cla=user&fun=editPage&staffId=".$staff['stid']."')\">新建</span>",
//                            ),
                            array(
                                "<span class='del-row-button' onclick=\"layer('" . self::page . "', 'userSet',{id:'" . $staff['stid'] . "'})\">新建</span>",
                            ),
                        ),
                    ]
                );
            }
            $field = array_merge($field, [
                L('staffProfiles.detail.picture') => array(
                    array(
                        $this->photo($photo),
                    ),
                ),
            ]);
            $json['html'] = "
            <div class='tab-box'>
                    <div class='tab-content'>
                    " . $this->tableShow($field) . clear . "
                    </div>
            </div>";
        }
        //返回
        $json['html'] .= <<<efo
<script>
//获取钉钉ID
function getDingId(id) {
     let con = setTimeout(function (){
        $("#loading", window.top.document).hide();
    },15000);
    $("#loading", window.top.document).show();
   $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getDingId',{id:id},function(res) {
       if (res.errcode ===0){
           $('[name=dingtalkId]').val(res.data);
       }else{
           warn(res.warn);
       }
         $("#loading", window.top.document).hide();
            clearTimeout(con);
   },'json')
}
function getWechatUserId(id) {
      let con = setTimeout(function (){
        $("#loading", window.top.document).hide();
    },15000);
       $("#loading", window.top.document).show();
   $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getWechatUserId',{id:id},function(res) {
       if (res.errcode ===0){
           $('[name=weChatUserId]').val(res.data);
       }else{
           warn(res.warn);
       }
         $("#loading", window.top.document).hide();
            clearTimeout(con);
   },'json')
}
</script>
efo;

        return json_encode($json, 320);
    }

    /**
     * 根据手机号获取钉钉ID
     *
     * @return bool|string
     */
    public function getDingId()
    {
        $id = $this->post('id');
        $staff = query('staff', " stid = '$id'");
        $obj = new workSignCheckClass();
        $userId = $obj->getbymobile($staff['tel']);
        if (empty($userId)) {
            $json['errcode'] = 1;
            $json['warn'] = L('staffProfiles.tip.find_none_ding');
        } else {
            $json['errcode'] = 0;
            $json['warn'] = '';
            $json['data'] = $userId;
        }
        return json_encode($json, 320);
    }

    /**
     * 根据手机号获取企业微信ID
     *
     * @return bool|string
     */
    public function getWechatUserId(): bool|string
    {
        $id = $this->post('id');
        $staff = query('staff', " stid = '$id'");
        $userId = $this->getWechatUserIdByTel($staff['tel']);
        if (empty($userId)) {
            $json['errcode'] = 1;
            $json['warn'] = L('staffProfiles.tip.find_none_wechat');
        } else {
            $json['errcode'] = 0;
            $json['warn'] = '';
            $json['data'] = $userId;
        }
        return json_encode($json, 320);
    }

    /**
     * 用户设置
     *
     * @return bool|string
     */
    public function userSet()
    {
        $staff = query('staff', " stid = '{$this->post('id')}'");
        $user = query('user', " stid = '$staff[stid]'");
        //获取角色
        $result = find(array('table' => "role order by list,time asc"));
        $roleOption = [];
        foreach ($result['array'] as $array) {
            $roleOption[$array['id']] = $array['name'];
        }
        //生成表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    must . L('staffProfiles.detail.username') . "：" => text(array("name" => "userName", "value" => $user['userName'] ?: $staff['name'])),
                ),
                array(
                    L('staffProfiles.detail.password') . "：" => hidden(['name' => 'password', 'value' => '']) . (!empty($user['uid']) ? "<span id='pwd'>***********</span><span class='spanButton' style='margin: 0 0 0 20px' id='resetPas'>" . L('staffProfiles.detail.pwd_reset_copy') . "</span>" : para('staffPas') . ' (初始密码)') . "
<script src='{$this->root}static/javascript/clipboard.min.js'></script>
<script>
 var clipboard = new ClipboardJS('#resetPas', {
        text: function() {
            resetPwd();
            return $('#pwd').html();
        }
    });
    clipboard.on('success', function(e) {
       msg('" . L('staffProfiles.detail.pwd_copy') . "')
    });
 function resetPwd(){
        $.ajax({
            url: root + 'control/adIndex.html?cla=staffProfiles&fun=resetPwd',
            type: 'post',
            data: {
                id : $('[name=\"id\"]').val()
            },
            dataType: 'json',
            async: false,
            success: function(res) {
                if(res.code == 1){
                    $('#pwd').html(res.data)
                }else{
                    msg(res.msg, 'error')
                }
            }
        });
 }
</script>
",
                ),
                array(
                    must . L('staffProfiles.detail.role') . "：" => "<pre>" . checkbox(array('name' => 'role', 'value' => $roleOption, 'checked' => json_decode($user['role'], true))) . "</pre>",
                ),
                array(
                    L('staffProfiles.table.text') . '：' => textarea(array('name' => 'text', 'class' => 'textarea', 'value' => $user['text'])),
                ),
            ),
        ));
        //返回
        return $this->layer(array("title" => L('staffProfiles.detail.user_stting'), "height" => 514, "width" => 900, "html" => $html));
    }

    /**
     * 重置密码
     *
     * @return bool|string
     */
    public function resetPwd(): bool|string
    {
        $id = $this->post('id');
        $staff = query(self::table, "stid = '$id'");
        $data['code'] = 0;
        $user = query('user', "stid = '$staff[stid]'");
        if (empty($staff['stid'])) {
            $data['msg'] = L('staffProfiles.detail.find_none_staff');
        } elseif (!$this->power(self::page, "edit")) {
            $data['msg'] = L('staffProfiles.tip.permission_edit_warn');
        } elseif (empty($user['uid'])) {
            $data['msg'] = L('staffProfiles.detail.find_none_account');
        } else {
            $password = para('staffPas');
            $data['warn'] = static::update([
                'table' => 'user',
                'field' => [
                    'password' => md5s($password),
                ],
                'where' => " uid = '$user[uid]' ",
            ]);
            if (in_array($data['warn'], ['更新成功', '新增成功'])) {
                $data = [
                    'msg' => L('staffProfiles.detail.pwd_reset'),
                    'data' => $password,
                    'code' => 1,
                ];
            }
        }
        return json_encode($data, 320);
    }

    /**
     * 用户设置
     *
     * @return bool|string
     */
    public function userSetEdit()
    {
        $id = $this->post('id');
        $staff = query(self::table, " stid = '" . $id . "' ");
        $user = query('user', " stid = '$staff[stid]'");
        $field = [
            'stid' => $staff['stid'],
            'name' => $staff['name'],
            'tel' => $staff['tel'],
            'userName' => $this->post('userName'),
            'role' => $this->post('role') ? json_encode($this->post('role'), 320) : [],
            'text' => $this->post('text'),
            'updateTime' => $this->time,
        ];
        $annotation = [
            'userName' => L('staffProfiles.detail.username'),
            'role' => L('staffProfiles.detail.role'),
        ];
        $rules = [
            'stid' => 'required',
            'name' => 'required',
            'userName' => 'required',
            'role' => 'required',
            'tel' => 'required|unsigned_int',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();

        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('staffProfiles.tip.permission_edit_warn');
        } elseif (empty($staff['stid'])) {
            $json['warn'] = L('staffProfiles.detail.find_none_staff');
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } elseif (static::total(array('table' => 'user', 'where' => "userName = '$field[userName]' and stid !='$staff[stid]'")) > 0) {
            $json['warn'] = L('staffProfiles.detail.exist_user');
        } else {
            // 非无限用户 设定用户数
            $users = (int)para('userNumberLimit');
            if ($users != -1) {
                // 已有用户数
                $total = static::total(['table' => 'user', 'where' => " 1=1 "]);
                if ($total >= $users) {
                    $json['warn'] = str_replace(['{{num}}'], [$users], L('setting.table.user_new_warn'));
                    goto resp;
                }
            }
            if (sqlNum('user', " (userName = '{$field['userName']}' OR tel = '{$field['tel']}') AND stid <> '$id'   ") > 0) {
                $json['warn'] = str_replace(['{{name}}', '{{tel}}'], [$field['userName'], $field['tel']], L('setting.table.user_repeat'));
                goto resp;
            }

            if (!$user['uid']) {
                $userNo = codeTemplateClass::generateCode('user', [
                    'prefix' => 'UID' . date('Ymd'),
                    'table' => 'user',
                    'field' => 'userNo',
                    'where' => '',
                ], $field);
                $field = array_merge($field, [
                    'uid' => $id,
                    'userNo' => $userNo,
                    'password' => md5s(para('staffPas')),
                    'operator' => $this->control['stid'],
                    'state' => '启用',
                    'time' => $this->time,
                ]);
                $json['warn'] = static::insert(["table" => 'user', "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => 'user',
                    "field" => $field,
                    "where" => "uid = '$user[uid]'",
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $staff['name'], $staff['stid']], L('staffProfiles.other.user_edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=setting&id=" . $staff['stid'];
            }
        }
        //返回
        resp:
        return json_encode($json, 320);
    }

    /**
     * 第三方账号设置
     *
     * @return bool|string
     */
    public function accountSet()
    {
        $staff = query('staff', " stid = '{$this->post('id')}'");
        $user = query('user', "stid = '$staff[stid]'");
        //生成表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    L('staffProfiles.detail.ding') . "：" => text(array("name" => "dingtalkId", "value" => $staff['dingtalkId'])) . "<span class='btn-borderless width35' onclick=\"getDingId('{$staff['stid']}')\">" . L('staffProfiles.detail.get') . "</span>" . componentClass::tipComponent(L('staffProfiles.detail.dingSameTel')),
                ),
                array(
                    L('staffProfiles.detail.wechat_id') . "：" => text(array("name" => "weChatUserId", "value" => $user['weChatUserId'])) . "<span class='btn-borderless width35' onclick=\"getWechatUserId('{$staff['stid']}')\">" . L('staffProfiles.detail.get') . "</span>" . componentClass::tipComponent(L('staffProfiles.detail.wechatSameTel')),
                ),
            ),
        ));
        //返回
        return $this->layer(array("title" => L('staffProfiles.detail.account_stting'), "height" => 245, "width" => 700, "html" => $html));
    }

    /**
     * 第三方账号设置
     *
     * @return bool|string
     */
    public function accountSetEdit()
    {
        $field = [
            'dingtalkId' => $this->post('dingtalkId'),
            'updateTime' => $this->time,
        ];

        $staff = query(self::table, " stid = '" . $this->post('id') . "' ");
        $user = query('user', "stid = '$staff[stid]'");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('staffProfiles.tip.permission_edit_warn');
        } elseif (empty($staff['stid'])) {
            $json['warn'] = L('staffProfiles.detail.find_none_staff');
        } elseif (!$user['uid'] && $this->post('weChatUserId')) {
            $json['warn'] = L('staffProfiles.detail.user_account_warn');
        } else {
            $this->startTrans();
            //更新员工档案
            $json['warn'] = update(array(
                "table" => "staff",
                "field" => $field,
                "where" => "stid = '$staff[stid]'",
            ));
            $bool = update(array('table' => 'user', 'field' => ['weChatUserId' => $this->post('weChatUserId')], 'where' => "stid = '$staff[stid]'"));
            if ($bool != '更新成功') {
                $json['warn'] = $bool;
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $staff['name'], $staff['stid']], L('staffProfiles.other.account_edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=setting&id=" . $staff['stid'];
            } else {
                $this->rollback();
            }
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 薪酬设置
     */
    public function salary()
    {
        $staff = query('staff', " stid = '{$this->post('id')}'");
        //生成表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    must . L('staffProfiles.detail.bankName') . "：" => text(array("name" => "bankName", "value" => $staff['bankName'])),
                ),
                array(
                    must . L('staffProfiles.detail.bankNo') . "：" => text(array("name" => "bankNum", "value" => $staff['bankNum'])),
                ),
                //            array(
                //                L('staffProfiles.detail.buy_insure')."：" => radio(array('name' => 'socialSecurity', 'value' => ['是', '否'], 'checked' => $staff['socialSecurity'] ?: '是')),
                //            ),
                //            array(
                //                L('staffProfiles.detail.insureNo')."：" => text(array("name" => "socialSecurityNum", "value" => $staff['socialSecurityNum'])),
                //            ),
                array(
                    L('staffProfiles.detail.personal_part') . "：" => text(array("name" => "personalFund", 'class' => 'text', 'unit' => static::$unit, "value" => $staff['personalFund'])),
                ),
                array(
                    L('staffProfiles.detail.company_part') . "：" => text(array("name" => "companyFund", 'class' => 'text', 'unit' => static::$unit, "value" => $staff['companyFund'])),
                ),
            ),
        ));
        //返回
        return $this->layer(array("title" => L('staffProfiles.detail.salary_setting'), "height" => 342, "html" => $html));
    }

    /**
     * 薪酬设置编辑
     *
     * @return bool|string
     */
    public function salaryEdit()
    {
        $field = [
            'bankName' => $this->post('bankName'),
            'bankNum' => $this->post('bankNum'),
            //            'socialSecurity' => $this->post('socialSecurity'),
            //            'socialSecurityNum' => $this->post('socialSecurityNum'),
            'personalFund' => $this->post('personalFund'),
            'companyFund' => $this->post('companyFund'),
            'updateTime' => $this->time,
        ];
        $annotation = [
            'bankName' => L('staffProfiles.detail.bankName'),
            'bankNum' => L('staffProfiles.detail.bankNo'),
        ];
        $rules = [
            'bankName' => 'required',
            'bankNum' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        $staff = query(self::table, " stid = '" . $this->post('id') . "' ");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('staffProfiles.tip.permission_edit_warn');
        } elseif (empty($staff['stid'])) {
            $json['warn'] = L('staffProfiles.detail.find_none_staff');
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            //更新员工档案
            $json['warn'] = update(array(
                "table" => "staff",
                "field" => $field,
                "where" => "stid = '$staff[stid]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $staff['name'], $staff['stid']], L('staffProfiles.other.salary_edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=setting&id=" . $staff['stid'];
            }
        }
        //返回
        return json_encode($json, 320);
    }


    /**
     * 样式
     */
    private function style(): string
    {
        return <<<eof
<style>
.tag-contain-title{border-bottom: 1px solid #d7d7d7;padding: 5px}
.tag-contain-title img{cursor: pointer}
.tag-list-ul>li{float: left;padding: 5px;margin: 5px}
.tag-contain{width: 500px;height: 400px;padding: 10px;border: 1px solid #d7d7d7;border-radius: 2px;position: relative;overflow: hidden}
.tag-contain-title-text{margin-left: 10px;font-size: 14px}
.tag-contain-ul li{margin: 5px 5px}
.tag-contain-foot{margin: 10px;padding: 10px;border-bottom: 1px solid #d7d7d7}
.tag-contain-body{width: 480px;height: 370px;margin: 0 auto}

}
</style>
eof;
    }

    public function evaluation()
    {
        $edit = $del = '';
        $id = $this->get('id');
        $staff = query('staff', "stid = '$id'");
        $sql = find(array("table" => "talent_pool_interview", "where" => " talentId in ('" . $id . "','" . $staff['talentId'] . "') order by recordDate desc "));
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取记录
        $html = "<ul class='tag-list-ul'>";
        $root = root;
        foreach ($sql['array'] as $array) {
            $creatName = self::findStaff($array['managerId']);

            $node = $array['node'] == '其他节点' ? $array['node'] . '-' . $array['nodeText'] : $array['node'];
            $all = find(array('table' => 'talent_pool_interview_detail', 'where' => "orderId = '$array[id]' order by list"));
            $xData = [];
            $yData = [];
            foreach ($all['array'] as $val) {
                $job_model_detail = query('job_model_detail', "id = '$val[modelId]'");
                $xData[] = [
                    'name' => $job_model_detail['name'],
                    'max' => 100,
                ];
                $yData[] = $val['score'];
            }

            $data = [
                "xData" => $xData,
                "yData" => [
                    'name' => '',
                    'data' => $yData,
                ],
            ];
            $salesPerformanceStatisticsClass = new salesPerformanceStatisticsClass();
            $echart = $salesPerformanceStatisticsClass->radarChart($data);
            if ($array['type'] == '评价记录') {
                $title = '员工档案';
                $directUrl = $url . "&fun=info&staffId={$array['talentId']}&id={$array['id']}";
                $infoUrl = $url . "&fun=infoDetail&id={$array['id']}";
                $editButton = "<img onclick=\"newIframe('{$title}','{$directUrl}')\"  src=\"{$root}img/control/edit.svg\">";
                $box = "<input name=\"faceId[]\" type=\"checkbox\" value=\"$array[id]\">";
            } else {
                $title = '人才库';
                $infoUrl = root . "control/adIndex.html?cla=talentPool&fun=infoDetail&id={$array['id']}";
                $editButton = '';
                $box = '';
            }
            $evaluation_node = L('staffProfiles.detail.evaluation_node');
            $evaluator = L('staffProfiles.detail.evaluator');
            $evaluate_date = L('staffProfiles.detail.evaluate_date');
            $html .= <<<efo
<li>
     <div class="tag-contain">
           <div class="tag-contain-title">
                 {$box}
                 {$editButton}
                 <img onclick="newIframe('{$title}','{$infoUrl}')" alt="" src="{$root}img/control/detail.svg">
                 <span class="tag-contain-title-text">{$evaluation_node}：$node</span>
                 <span class="tag-contain-title-text">{$evaluator}：$creatName</span>
                 <span class="tag-contain-title-text">{$evaluate_date}：{$array['recordDate']}</span>
           </div>
           <div class="tag-contain-body">
           {$echart}
           </div>
     </div>
</li>
efo;
        }
        $no_data = L('staffProfiles.detail.no_data');
        if (is_array($sql['array']) && count($sql['array']) == 0) {
            $html .= <<<eof
<div class="container-no">
                    <img class="container-no-img" src="{$this->root}img/control/department-no.svg">
                    <p class="center gray">$no_data</p>
                </div>
eof;
        }

        $html .= <<<efo
</ul>
efo;
        $html .= $this->style();


        if ($this->power(self::page, "interviewEdit")) {
            $edit = "<span class='spanButton' title='" . L('job.model.edit') . "' onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=info&staffId={$id}')\">" . L('job.model.edit') . "</span>\n";
        }
        if ($this->power(self::page, "interviewDel")) {
            $del = "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'delInterview'})\">" . L('staffProfiles.button.del') . "</span>\n";
        }
        $json['html'] = "<div class='tab-button flex-box'>" . $edit . $del . "</div>" .
            "<script src='{$this->root}static/javascript/echarts.min.js'></script>
            <form name='faceForm'>" . $html . "</form>";
        return json_encode($json, 320);
    }

    /*详情页*/
    public function infoDetail(): string
    {
        $info = query('talent_pool_interview', " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('staffProfiles.detail.find_none_ev_record');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "interviewEdit")) {
                //按钮
                $button[] = [
                    "name" => L('staffProfiles.button.edit'),
                    "type" => "顶部页卡",
                    "title" => L('staffProfiles.button.edit'),
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=info&staffId=' . $info['talentId'] . '&id=' . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, "interviewDel")) {
                //按钮
                $button[] = [
                    "name" => L('staffProfiles.button.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'delInterview', "id" => $info['id']],
                ];
            }

            $result = find(array('table' => 'talent_pool_interview_detail', 'where' => "orderId = '$info[id]' order by list asc"));
            $tr[] = [
                L('job.model.projectName'),
                L('job.model.projectText'),
                L('job.model.evaluate_item'),
                L('job.model.percent'),
                L('staffProfiles.detail.score'),
            ];
            $totalScore = 0;
            foreach ($result['array'] as $array) {
                $mx = query('job_model_detail', "id = '$array[modelId]'");
                $tr[] = [
                    $mx['name'],
                    $mx['text'],
                    $array['itemName'],
                    ($mx['proportion'] * 100) . '%',
                    "<span class='score'>{$array['score']}</span>",
                ];
                $array['score'] = $array['score'] ?: 0;
                $totalScore += $array['score'] * $mx['proportion'];
            }
            $tr[] = [L('staffProfiles.detail.all_score'), ' ', ' ', ' ', "<span id='totalScore'>" . ($totalScore ?: '---') . "</span>"];
            $staff = query(self::table, "stid = '$info[talentId]'");
            $talent = query('talent_pool', "id = '$staff[talentId]'");
            $job = query('job', "id = '$staff[jobId]'");
            $staffEntryRecord = query('staff_entry_record', "talentId = '$staff[talentId]' order by time desc");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                L('staffProfiles.detail.evd_information') => array(
                    array(
                        L('staffProfiles.table.name') => $talent['name'],
                        L('staffProfiles.table.sex') => $talent['sex'],
                        L('staffProfiles.table.age') => $this->age($talent['birthDay']),
                        L('staffProfiles.table.college') => $talent['college'] ,
                    ),
                    array(
                        L('staffProfiles.table.major') => $talent['major'],
                        L('staffProfiles.table.education') => $talent['education'],
                        L('staffProfiles.table.department') . "：" => departmentClass::getTypeName($job['departmentId']),
                        L('staffProfiles.table.job') . '：' => $job['name'],
                    ),
                    array(
                        L('staffProfiles.table.entryDate') . '：' => $staffEntryRecord['entryDate'],
                    ),
                ),
                L('staffProfiles.detail.ev_information') => array(
                    array(
                        L('staffProfiles.detail.evaluate_date') => $info['recordDate'],
                        L('staffProfiles.detail.evaluator') => self::findStaff($info['managerId']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => L('staffProfiles.detail.assessment'),
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'showSort' => true)),
            ]);
            $data['html'] .= $this->tableShow(array(
                L('staffProfiles.detail.all_evaluation') => array(
                    array(
                        L('staffProfiles.detail.all_evaluation') => $info['evaluation'],
                    ),
                    array(
                        L('staffProfiles.detail.evaluation_result') => $info['opinion'],
                    ),
                ),
            ));
            $data['html'] .= $this->detailBlock([
                L('staffProfiles.table.enclosure') => fileUploadClass::showFile($info['id'])
            ]);

            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    public function info()
    {
        $id = $this->get('id') ?: suiji();
        $stid = $this->get('staffId');
        $info = query('talent_pool_interview', " id = '" . $id . "' ");
        $staff = query(self::table, "stid = '$stid'");
        $talent = query('talent_pool', "id = '$staff[talentId]'");
        $staffEntryRecord = query('staff_entry_record', "talentId = '$staff[talentId]' order by time desc");
        //按钮
        $button[] = [
            "name" => L('staffProfiles.table.save'),
            "type" => "点击事件",
            "cla" => $this->get('cla'),
            "fun" => "subForm('" . self::page . "InfoForm',root+'control/adIndex.html?cla=" . self::page . "&fun=infoEdit')",
            "post" => ["id" => $id],
            'style' => 'li-btn-blue-bg',
        ];
        $job = query('job', "id = '$staff[jobId]'");
        //能力评定
        $tr[] = [
            '',
            L('job.model.projectName'),
            L('job.model.projectText'),
            L('job.model.evaluate_item'),
            L('job.model.percent'),
            L('staffProfiles.detail.score'),
        ];
        $all = find(array('table' => 'job_model_detail', 'where' => "jobId = '$staff[jobId]' order by time asc"));
        $totalScore = 0;
        foreach ($all['array'] as $k=>$array) {
            $mx = query('talent_pool_interview_detail', "orderId = '$info[id]' and modelId = '$array[id]'");
            $tr[] = [
                componentClass::tablePperation($k+1,"").
                hidden(array('name' => 'detailId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'proportion[]', 'value' => $array['proportion'])),
                $array['name'],
                $array['text'],
                repeatSelect(array('name' => 'itemName[]', 'change' => 'getScore', 'sqlField' => 'name', 'sqlForm' => "job_model_item where orderId = '$array[id]' order by any_value(list)", 'title' => L('staffProfiles.table.choose'), 'value' => $mx['itemName'])),
                ($array['proportion'] * 100) . '%',
                "<span class='score'>{$mx['score']}</span>",
            ];
            $mx['score'] = $mx['score'] ?: 0;
            $totalScore += $mx['score'] * $array['proportion'];
        }
        $tr[] = [' ', L('staffProfiles.detail.all_score'), ' ', ' ', ' ', "<span id='totalScore'>" . ($totalScore ?: '---') . "</span>"];
        $nodeOption = explode('，', para('nodeOption'));
        $nodeOption[] = '其他';
        $data['button'] = $this->tableShowButton($button);
        //表单
        $body = $this->edit4([
            L('staffProfiles.detail.evd_information') => [
                [
                    L('staffProfiles.table.name') . "：" => $staff['name'],
                    L('staffProfiles.table.sex') . "：" => $talent['sex'],
                    L('staffProfiles.table.age') . '：' => $this->age($talent['birthDay']),
                    L('staffProfiles.table.college') . "：" => $talent['college'],
                ],
                [
                    L('staffProfiles.table.major') . "：" => $talent['major'],
                    L('staffProfiles.table.education') . "：" => $talent['education'],
                    L('staffProfiles.table.department') . "：" => departmentClass::getTypeName($job['departmentId']),
                    L('staffProfiles.table.job') . '：' => $job['name'],
                ],
                [
                    L('staffProfiles.table.entryDate') . '：' => $staffEntryRecord['entryDate'],
                ],
            ],
            L('staffProfiles.detail.ev_information') => [
                [
                    must . L('staffProfiles.detail.evaluate_date') . "：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    must . L('staffProfiles.detail.evaluator') . "：" => selectMultiple(array('name' => 'managerId', 'value' => $info['managerId'] ?: self::$stid, 'title' => L('staffProfiles.table.choose'), 'sqlId' => 'stid', 'sqlField' => 'name', 'table' => 'staff', 'where' => "state !='离职' order by orderNo asc")),
                    must . L('staffProfiles.detail.evaluation_node') . "：" => radio(array('name' => 'node', 'value' => $nodeOption, 'checked' => $info['node'])) . "&nbsp;" . text(array('name' => 'nodeText', 'title' => '其他节点说明', 'value' => $info['nodeText'])),
                ],
            ]
        ]);
        $body .= $this->editList([
            'title' => L('staffProfiles.detail.assessment'),
            'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'displayFields' => false)),
        ]);
        $body .= $this->editBlock([
            '附件' => fileUploadClass::addFileComponent($id, '评价附件', self::page, self::page . 'EditForm')
        ]);
        $body .= $this->edit4([
            L('staffProfiles.detail.all_evaluation') => [
                [
                    must . L('staffProfiles.detail.evaluation_result') . "：" => radio(array('name' => 'opinion', 'checked' => $info['opinion'] ?: '合格', 'value' => ['合格', '不合格'])),
                ],
                [
                    must . L('staffProfiles.detail.all_evaluation') . "：" => textarea(array('name' => 'evaluation', 'class' => 'textarea', 'value' => $info['evaluation'])),
                ],
            ]
        ]);
        $body .= $this->editBlock([
            L('staffProfiles.table.enclosure') => fileUploadClass::addFileComponent($info['id'], '评价记录', self::page, self::page . 'InfoForm')
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(array('name' => 'id', 'value' => $id)) . hidden(array('name' => 'staffId', 'value' => $this->get('staffId'))),
            'button' => ' ',
        ]);

        //返回
        $data['html'] .= <<<eof
<script>
function getScore(e) {
  let val = e.value;
  let modelId = $(e).parent().parent().find("[name='detailId[]']").val();
  $.post(root+'control/adIndex.html?cla=talentPool&fun=getScore',{name:val,modelId:modelId},function(res) {
      $(e).parent().parent().find(".score").html(res.data.score);
      $(e).parent().parent().find("[name='proportion[]']").val(res.data.rate);
      addScore();
  },'json')
}
function addScore(){
    let num = 0;
    let proportion = 0;
    $(".score").each(function() {
        proportion = Number($(this).parent().parent().find("[name='proportion[]']").val())
       num+=Number($(this).html())*proportion;
    })
    $("#totalScore").html(num.toFixed(1));
}
</script>
eof;

        return $this->tab($data);
    }

    public function infoEdit()
    {
        $id = $this->post('id');
        $info = query('talent_pool_interview', " id = '$id'");
        $staff = query(self::table, "stid = '" . $this->post('staffId') . "'");
        $field = [
            'recordDate' => $this->post('recordDate'),
            'managerId' => $this->post('managerId'),
            'evaluation' => $this->post('evaluation'),
            'opinion' => $this->post('opinion'),
            'workFlow' => $this->post('workFlow'),
            'node' => $this->post('node'),
            'nodeText' => $this->post('node') == '其他' ? $this->post('nodeText') : '',

        ];
        $annotation = [
            'recordDate' => L('staffProfiles.detail.evaluate_date'),
            'managerId' => L('staffProfiles.detail.evaluator'),
            'evaluation' => L('staffProfiles.detail.all_evaluation'),
            'opinion' => L('staffProfiles.detail.evaluation_result'),
            'node' => L('staffProfiles.detail.evaluation_node'),
        ];
        $rules = [
            'recordDate' => 'required|date',
            'managerId' => 'required',
            'evaluation' => 'required',
            'opinion' => 'required',
            'node' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $detailIdArr = $this->post('detailId') ?? [];
        $itemNameArr = $this->post('itemName');
        //附件
        $fileIdArr = $this->post('fileId');
        //判断
        if (!$this->power(self::page, "interviewEdit")) {
            $json['warn'] = L('staffProfiles.tip.staffEvEdit');
        } elseif (empty($staff['stid'])) {
            $json['warn'] = L('staffProfiles.detail.find_none_staff');
        } elseif (static::is_null_array($detailIdArr)) {
            $json['warn'] = L('staffProfiles.tip.find_none_item');
        } elseif (static::is_null_array($itemNameArr)) {
            $json['warn'] = L('staffProfiles.tip.evaluate_warn');
        } elseif ($field['node'] == '其他' && empty($field['nodeText'])) {
            $json['warn'] = L('staffProfiles.tip.evaluate_item_warn');
        } else {
            $this->startTrans();//开启事务
            if (empty($info['id'])) {
                $manager = query('staff', "stid = '$field[managerId]'");
                $job = query('job', "id = '$manager[jobId]'");
                $field = array_merge($field, [
                    'id' => $id,
                    'stid' => self::$stid,
                    'talentId' => $staff['stid'],
                    'type' => '评价记录',
                    'managerDept' => departmentClass::getTypeName($job['departmentId']),
                ]);
                $json['warn'] = static::insert(array('table' => 'talent_pool_interview', 'field' => $field));
            } else {
                $json['warn'] = static::update(array(
                    'table' => 'talent_pool_interview',
                    'field' => $field,
                    'where' => "id = '$info[id]'",
                ));
            }
            delete(array('table' => 'talent_pool_interview_detail', 'where' => " orderId = '$id'"));
            foreach ($detailIdArr as $k => $val) {
                $job_model_item = query('job_model_item', "orderId = '" . $val . "' and name = '" . $itemNameArr[$k] . "'");
                $bool = static::insert(array(
                    'table' => 'talent_pool_interview_detail',
                    'field' => [
                        'id' => suiji(),
                        'orderId' => $id,
                        'modelId' => $val,
                        'itemName' => $itemNameArr[$k],
                        'score' => $job_model_item['score'],
                    ],
                ));
                if ($bool != '新增成功') {
                    $json['warn'] = L('staffProfiles.tip.editFailed');
                    break;
                }
            }
            //添加主表ID到附件表
            if (is_array($fileIdArr)) {
                $bool = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                if ($bool != '更新成功') {
                    $json['warn'] = $bool;
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();//提交事务
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $staff['name'], $id], L('staffProfiles.tip.interview_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=evaluation&id=" . $staff['stid'];
            } else {
                $this->rollback();//回滚
            }
        }
        resp:
        return json_encode($json, 320);
    }


    /**
     * 获取角色名称
     *
     * @param $role
     * @return string
     */
    public function findRoleName($role): string
    {
        $roleArr = json_decode($role, true);
        $roleText = '';
        foreach ($roleArr as $roleId) {
            $role = query('role', " id = '$roleId'");
            $roleText .= ',' . $role['name'];
        }
        return $roleText ? ltrim($roleText, ',') : '';
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'delInterview':
                $act = 'del';
                $msg = L('staffProfiles.tip.del_evaluate_record');
                $title = self::table . 'DeleteInterview';
                $function = 'deleteMx';
                $form = self::page . 'OperateForm, faceForm';
                $power = '';
                break;
            case 'recover':
                $word = true;
                $act = 'edit';
                $msg = L('staffProfiles.tip.confirmWork');
                $title = L('staffProfiles.tip.is_confirm_work');
                $form = self::page . 'OperateForm,detailForm';
                $function = 'recover';
                break;

            default:
                $act = 'del';
                $msg = L('staffProfiles.tip.del_staff');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 确认上岗
     *
     * @return bool|string
     */
    public function recover(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, " stid = '$id'");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('staffProfiles.tip.permission_edit_warn');
        } elseif (empty($info['stid'])) {
            $json['warn'] = L('staffProfiles.detail.find_none_staff');
        } else {
            $field = [
                'state' => '转正',
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " stid ='$id'"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加上岗日期到记录表中
                $staffStayRecord = query('staff_stay_record', " staffId = '$info[stid]' and isConfirm = 1 and state = '已通过' order by endDate desc,time desc");
                update(array('table' => 'staff_stay_record', 'field' => ['recoverTime' => $this->time], 'where' => " id = '$staffStayRecord[id]'"));
                //生成员工变动记录
                $obj = new staffEntryRecordClass();
                $obj->insertStaffStateRecord($info['stid'], '上岗', $staffStayRecord['id'], $this->date);
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $info['name'], $id], L('staffProfiles.other.recover_edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    public function deleteMx()
    {
        $array = $this->post('faceId') ?? $this->post('id');
        if (!$this->power(self::page, "interviewDel")) {
            $json['warn'] = L('staffProfiles.tip.permission_evaluate_del_warn');
        } elseif (empty($array)) {
            $json['warn'] = L('staffProfiles.tip.no_data_choose');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query('talent_pool_interview', " id = '$id' ");
                if ($info['type'] == '评价记录') {
                    delete(array('table' => 'talent_pool_interview_detail', 'where' => "orderId = '$id'"));
                    $all = find(array('table' => "file", "where" => "targetId = '$id'"));
                    foreach ($all['array'] as $val) {
                        fileDelete($val['src']);
                    }
                    //删除附件
                    delete(array("table" => 'file', "where" => " targetId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => 'talent_pool_interview', "where" => " id = '$id' "));
                    //返回
                    $warn = L('job.other.delete_success');
                    $x++;
                } else {
                    $warn = L('staffProfiles.other.del_ev_failed');
                }
                $text .= L('staffProfiles.other.ev_id') . "【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('staffProfiles.other.del_ev_text')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('staffProfiles.other.del_ev_log'));
            $json['warn'] = 2;
        }
        $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=evaluation&id=" . ($info['talentId'] ?? '');
        return json_encode($json, 320);
    }

    /**
     * 是否拥有超级管理员权限(不可删除一般指超级管理员权限)
     *
     * @return bool
     */
    public static function forceDel()
    {
        $roleArr = (array)json_decode(self::$user['role'], true);
        $all = find(['table' => 'role', 'where' => "isDel = 1"]);
        foreach ($all['array'] as $role) {
            if (in_array($role['id'], $roleArr)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 删除员工
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?: $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('staffProfiles.tip.permission_del_warn');
        } elseif (empty($array)) {
            $json['warn'] = L('staffProfiles.tip.no_data_choose');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];

            $force = self::forceDel();
            foreach ($array as $id) {
                $info = query(self::table, " stid = '$id' ");
                $user = query('user', "stid = '$id'");
                if (!$force && $info['workFlow'] == '已复核' && $info['state'] != '离职') {
                    $warn = L('staffProfiles.other.staff_del_state_warn');
                } elseif (!$force && $info['workFlow'] == '已复核' && static::total(array('table' => 'examine', 'where' => "node like '%$id%'")) > 0) {
                    $warn = L('staffProfiles.other.staff_del_audit_warn');
                } elseif ($user['isDel']) {
                    $warn = '此员工为系统不可删除账户';
                } else {
                    //操作记录
                    delete(array("table" => 'staff_state_record', "where" => " stid = '$id' "));
                    //人才库
                    delete(array("table" => 'talent_pool', "where" => " id = '$info[talentId]' "));
                    //劳务合同
                    delete(array("table" => 'staff_contract', "where" => " staffId = '$id' "));
                    //劳务合同变更记录
                    delete(array("table" => 'staff_contract_change', "where" => " contractId in (select id from staff_contract where staffId = '$id')"));
                    //社保记录
                    delete(array("table" => 'staff_insure', "where" => " staffId = '$id' "));
                    //入职记录
                    delete(array("table" => 'staff_entry_record', "where" => " talentId = '$info[talentId]' "));
                    //考勤记录
                    delete(array('table' => 'work_sign', 'where' => "stid = '$id'"));
                    //用户表
                    delete(array('table' => 'user', 'where' => "stid = '$id'"));
                    //转正记录表
                    delete(array('table' => 'staff_formal', 'where' => "staffId = '$id'"));
                    //工伤记录表
                    delete(array('table' => 'staff_injury', 'where' => "staffId = '$id'"));
                    //离职记录表
                    delete(array('table' => 'staff_quit_record', 'where' => "staffId = '$id'"));
                    //停薪留职表
                    delete(array('table' => 'staff_stay_record', 'where' => "staffId = '$id'"));
                    //车间考勤员工表
                    delete(array('table' => 'workshop_clock_staff', 'where' => "stid = '$id'"));
                    //工序报工员工表
                    delete(array('table' => 'process_report_staff', 'where' => "stid = '$id'"));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " stid = '$id' "));
                    //返回
                    $warn = L('job.other.delete_success');
                    $x++;
                }
                $text .= L('staffProfiles.other.staff') . "【{$info['name']}】，ID【" . $info['stid'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('staffProfiles.other.staff_del_text')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('staffProfiles.other.staff_del_log'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'员工编号',
                    'aliasName'=>'员工编号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'性别',
                    'aliasName'=>'性别',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'手机号码',
                    'aliasName'=>'手机号码',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'身份证号',
                    'aliasName'=>'身份证号',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'学历',
                    'aliasName'=>'学历',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'职位编码',
                    'aliasName'=>'职位编码',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'职位名称',
                    'aliasName'=>'职位名称(在职位列表中查找)',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'入职日期',
                    'aliasName'=>'入职日期(日期)',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'试用期至',
                    'aliasName'=>'试用期至(日期)',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'劳动报酬',
                    'aliasName'=>'劳动报酬',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'社会保险',
                    'aliasName'=>'社会保险',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'合同期限类型',
                    'aliasName'=>'合同期限类型',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'合同期限',
                    'aliasName'=>'合同期限(月)',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'直属上级名称',
                    'aliasName'=>'直属上级名称',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'直属上级编号',
                    'aliasName'=>'直属上级编号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'毕业院校',
                    'aliasName'=>'毕业院校',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'邮箱',
                    'aliasName'=>'邮箱',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'期望工作地点',
                    'aliasName'=>'期望工作地点',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'期望薪资',
                    'aliasName'=>'期望薪资',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'出生年月',
                    'aliasName'=>'出生年月(日期)',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'民族',
                    'aliasName'=>'民族',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'籍贯',
                    'aliasName'=>'籍贯',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'身高',
                    'aliasName'=>'身高(cm)',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'体重',
                    'aliasName'=>'体重(kg)',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'健康状况',
                    'aliasName'=>'健康状况',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'专业',
                    'aliasName'=>'专业',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'职称',
                    'aliasName'=>'职称',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'参加工作时间',
                    'aliasName'=>'参加工作时间',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'婚姻状况',
                    'aliasName'=>'婚姻状况',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'政治面貌',
                    'aliasName'=>'政治面貌',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'户籍地址',
                    'aliasName'=>'户籍地址',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'户口性质',
                    'aliasName'=>'户口性质',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'通讯住址',
                    'aliasName'=>'通讯住址',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'邮政编码',
                    'aliasName'=>'邮政编码',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'紧急联系人姓名',
                    'aliasName'=>'紧急联系人姓名',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'与紧急联系人关系',
                    'aliasName'=>'与紧急联系人关系',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'紧急联系人手机号',
                    'aliasName'=>'紧急联系人手机号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'竞业禁止协议',
                    'aliasName'=>'竞业禁止协议（有/无，不填默认无）',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'工作备注',
                    'aliasName'=>'工作备注',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'转正日期',
                    'aliasName'=>'转正日期',
                    'isMust'=>false,
                ],
            ]
        };
    }

    /**
     * 获取单元格列字母A-AP
     * @return array
     */
    public function getAllColumns() {
        $columns = array();
        for ($i = 1; $i <= 42; $i++) { // 42是A-AP列的数量（AP列是第42列）
            $column = "";
            $dividend = $i;

            while ($dividend > 0) {
                $module = ($dividend - 1) % 26;
                $column = chr(65 + $module) . $column;
                $dividend = intval(($dividend - $module) / 26);
            }

            $columns[] = $column;
        }

        return $columns;
    }
    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'员工编号',
                    'aliasName'=>'员工编号',
                ],
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                ],
                [
                    'columnName'=>'性别',
                    'aliasName'=>'性别',
                ],
                [
                    'columnName'=>'手机号码',
                    'aliasName'=>'手机号码',
                ],
                [
                    'columnName'=>'职位',
                    'aliasName'=>'职位',
                ],
                [
                    'columnName'=>'直属上级',
                    'aliasName'=>'直属上级',
                ],
                [
                    'columnName'=>'入职日期',
                    'aliasName'=>'入职日期',
                ],
                [
                    'columnName'=>'试用期至',
                    'aliasName'=>'试用期至',
                ],
                [
                    'columnName'=>'期望工作地点',
                    'aliasName'=>'期望工作地点',
                ],
                [
                    'columnName'=>'期望薪资',
                    'aliasName'=>'期望薪资',
                ],
                [
                    'columnName'=>'身份证号',
                    'aliasName'=>'身份证号',
                ],
                [
                    'columnName'=>'出生年月',
                    'aliasName'=>'出生年月',
                ],
                [
                    'columnName'=>'民族',
                    'aliasName'=>'民族',
                ],
                [
                    'columnName'=>'籍贯',
                    'aliasName'=>'籍贯',
                ],
                [
                    'columnName'=>'邮箱',
                    'aliasName'=>'邮箱',
                ],
                [
                    'columnName'=>'身高',
                    'aliasName'=>'身高(cm)',
                ],
                [
                    'columnName'=>'体重',
                    'aliasName'=>'体重(kg)',
                ],
                [
                    'columnName'=>'健康状况',
                    'aliasName'=>'健康状况',
                ],
                [
                    'columnName'=>'学历',
                    'aliasName'=>'学历',
                ],
                [
                    'columnName'=>'专业',
                    'aliasName'=>'专业',
                ],
                [
                    'columnName'=>'毕业院校',
                    'aliasName'=>'毕业院校',
                ],
                [
                    'columnName'=>'参加工作时间',
                    'aliasName'=>'参加工作时间',
                ],
                [
                    'columnName'=>'婚姻状况',
                    'aliasName'=>'婚姻状况',
                ],
                [
                    'columnName'=>'政治面貌',
                    'aliasName'=>'政治面貌',
                ],
                [
                    'columnName'=>'邮政编码',
                    'aliasName'=>'邮政编码',
                ],
                [
                    'columnName'=>'户籍地址',
                    'aliasName'=>'户籍地址',
                ],
                [
                    'columnName'=>'户口性质',
                    'aliasName'=>'户口性质',
                ],
                [
                    'columnName'=>'通讯住址',
                    'aliasName'=>'通讯住址',
                ],
                [
                    'columnName'=>'紧急联系人姓名',
                    'aliasName'=>'紧急联系人姓名',
                ],
                [
                    'columnName'=>'与紧急联系人关系',
                    'aliasName'=>'与紧急联系人关系',
                ],
                [
                    'columnName'=>'紧急联系人手机号',
                    'aliasName'=>'紧急联系人手机号',
                ],
                [
                    'columnName'=>'竞业禁止协议',
                    'aliasName'=>'竞业禁止协议',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
            ]
        };
    }
}
